|Temporary Location for Coding Standards Review|
The coding standards official location can be found in the Zend Framework Online Manual and are copied here for review and updates before being placed back into DocBook format in Subversion. The manual also contains translated versions that are not available here.
- 1 Overview
- 2 PHP File Formatting
- 3 Inline Documentation
- 3.1 Indenting
- 3.2 File Header
- 3.3 Require Once
- 3.4 Class Header
- 3.5 Function Header
- 3.6 Inline Documentation
- 4 Naming Conventions
- 4.1 Abstractions Used in API (Class Interfaces)
- 4.2 Classes
- 4.3 Interfaces
- 4.4 Filenames
- 4.5 Functions and Methods
- 4.5.1 Optional Parameters
- 4.6 Variables
- 4.7 Constants
- 4.8 Booleans and the NULL Value
- 5 Coding style
- 5.1 Global
- 6 Appendix: Automatted tests
This document provides the coding standards and guidelines for developers and teams working on or with the Zend Framework. The subjects covered are:
- PHP File Formatting
- Inline Documentation
- Naming Conventions
- Coding Style
- Errors and Exceptions
- Appendix: Automatted tests
Good coding standards are important in any development project, particularly when multiple developers are working on the same project. Having coding standards helps to ensure that the code is of high quality, has fewer bugs, and is easily maintained.
Abstract goals we strive for:
- extreme simplicity
- tool friendliness, such as use of method signatures, constants, and patterns that support IDE tools and auto-completion of method, class, and constant names.
When considering the goals above, each situation requires an examination of the circumstances and balancing of various trade-offs.
For PHP files the closing tag ("?>") is to be omitted. It is not required by PHP, and omitting it prevents trailing whitespace from being accidentally injected into the output.
Inclusion of arbitrary binary data as permitted by __HALT_COMPILER() is prohibited from any Zend framework PHP file or files derived from them. Use of this feature is only permitted for special installation scripts.
Also using the closing tag to generate HTML output within a method is omitted. Instead use heredoc syntax if needed.
Use an indent of 4 spaces with no tab characters. Editors should be configured to treat tabs as spaces in order to prevent injection of tab characters into the source code.
Multiple assignments must have the same indentation.
The target line length is 80 characters; i.e., developers should aim keep code as close to the 80-column boundary as is practical. However, longer lines are acceptable. The maximum length of any line of PHP code is 120 characters.
Line termination is the standard way for Unix text files. Lines must end only with a linefeed (LF). Linefeeds are represented as ordinal 10, or hexadecimal 0x0A.
Do not use carriage returns (CR) like Macintosh computers (0x0D).
Do not use the carriage return/linefeed combination (CRLF) as Windows computers (0x0D, 0x0A).
Lines should not contain trailing spaces. In order to facilitate this convention, most editors can be configured to strip trailing spaces, such as upon a save operation.
All docblock parts which are not keywords have to be under each other with the same indenting.
Also when describing parameters the keywords, parameters, and description have to have the same indenting.
Each file which is delivered with the Zend Framework must have the following header block:
When other filestypes are used like *.SH, *.BAT, *.JS and so on, the header block must also be contained as header comment. Only when a filetype does not support comments like *.CSS the header block can be omited.
_COMPONENT_ has to be the component which this file is part of it, for example Zend_Db or Zend_Gdata. There are only two exceptions:
All demo files are located in the component Demos and all classes in the incubator have to be handled as if they are in core... so "incubator/Zend/Class" becomes the component "Zend_Class"
_SEPARATION_ has to be a logical separation within this component. Logical separations occur when there are several directories which seperate parts of the same component. The component name if contained in the separation has to be omitted. For example a file which is in Zend/Db/Adapters/* will have Adapters as separation and Zend_Db as component. Only files which are in the main directory of the framework which is "Zend" can omit the subpackage.
_ENDDATE_ has to be the actual year of the release of the framework.
All classes/files which are required must contain a @see clause:
This clause has also to be added when a require_once is in the code and not in the file header.
A class must have a class header looking like this:
The discription explains what this class does.
_COMPONENT_ has to be the component which this file is part of it, for example Zend_Db or Zend_Gdata.
_SEPARATION_ has to be a logical separation within this component. Logical separations occur when there are several directories which seperate parts of the same component. For example a file which is in Zend/Db/Adapters/* will have "Zend_Db_Adapters" as separation. There is only one exception: All files which are part of the demos directory have to be in the Demos subpackage. Only files which are in the main directory of the framework which is "Zend" can omit the subpackage.
_USES_ has to be the extended or implemented classname. A class which "extends Zend_MyClass" must have a clause @uses Zend_MyClass. Also a class which "implementes Zend_MyClass" must have a clause @uses Zend_MyClass.
_ENDDATE_ has to be the actual year of the release of the framework.
Each function must have a function header.
The header has to look like this:
All parameters of the function must be available.
The following types are allowed:
- Zend_xxx (must be an existing class)
If more than one type could be used then the possible types have to be seperated with "|" like show above.
If a parameter can be omitted the description must prepend a (optional) like shown above.
If the function can throw an exception the @throws clause must be declared.
Multiple exception types must be seperated with "|".
A @return clause must always be defined.
If multiple types can be returned the types must be seperated with "|".
An description can be appended, but is not necessary.
If the class itself is returned (fluid interface) then the description
must be added
If the function does not return any value then the return value must be set to null
Documentation within a method is good practice and should be done to increase readability of the code.
The only acceptable syntax is phpdoc ("/**") or pearl ("//").
The usage of the ("#") Syntax is not allowed.
When creating an API for use by application developers (as opposed to Zend Framework internal developers), if application developers must identify abstractions using a compound name, separate the names using underscores, not camelCase. For example, the name used for the MySQL PDO driver is 'pdo_mysql', not 'pdoMysql'. When the developer uses a string, normalize it to lowercase. Where reasonable, add constants to support this (e.g. PDO_MYSQL).
The Zend Framework employs a class naming convention whereby the names of the classes directly map to the directories in which they are stored. The root level directory of the Zend Framework is the "Zend/" directory, under which all classes are stored hierarchically.
Class names may only contain alphanumeric characters. Numbers are permitted in class names but are discouraged. Underscores are only permitted in place of the path separator. For example, the filename "Zend/Db/Table.php" must map to the class name "Zend_Db_Table".
If a class name is comprised of more than one word, the first letter of each new word must be capitalized. Successive capitalized letters are not allowed; e.g., a class "Zend_PDF" is not allowed, while "Zend_Pdf" is acceptable.
Zend Framework classes that are authored by Zend or one of the participating partner companies and distributed with the Framework must always start with "Zend_" and must be stored under the "Zend/" directory hierarchy accordingly.
These are examples of acceptable names for classes:
Code that operates with the framework but is not part of the framework, such as code written by a framework end-user and not Zend or one of the framework's partner companies, must never start with "Zend_".
Interface classes must follow the same conventions as other classes (see above), but must end with "_Interface", such as in these examples:
For all other files, only alphanumeric characters, underscores, and the dash character ("-") are permitted. Spaces are prohibited.
Any file that contains any PHP code must end with the extension ".php". These examples show the acceptable filenames for containing the class names from the examples in the section above:
File names must follow the mapping to class names described above.
Function names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged.
Function names must always start with a lowercase letter. When a function name consists of more than one word, the first letter of each new word must be capitalized. This is commonly called the "camelCaps" method.
Verbosity is encouraged. Function names should be as illustrative as is practical to enhance understanding.
These are examples of acceptable names for functions:
For object-oriented programming, accessors for object members should always be prefixed with either "get" or "set". When using design patterns, such as the Singleton or Factory patterns, the name of the method should contain the pattern name where practical to make the pattern more readily recognizable.
Though function names may not contain the underscore character, class methods that are declared as protected or private must begin with a single underscore, as in the following example:
Functions in the global scope, or "floating functions," are permitted but discouraged. It is recommended that these functions be wrapped in a class and declared static.
Functions or variables declared with a "static" scope in a class generally should not be "private", but protected instead. Use "final" if the function should not be extended.
The opening brace of functions and methods has to be in the next line.
Use "null" as the default value instead of "false", for situations like this:
public function foo($required, $optional = null)
when $optional does not have or need a particular default value.
However, if an optional parameter is boolean, and its logical default value should be true, or false, then using true or false is acceptable.
Variable names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in variable names but are discouraged.
For class member variables that are declared with the private or protected construct, the first character of the variable name must be a single underscore. This is the only acceptable usage of an underscore in a variable name. Member variables declared as "public" may never start with an underscore. For example:
Like function names, variable names must always start with a lowercase letter and follow the "camelCaps" capitalization convention.
Verbosity is encouraged. Variable names should always be as verbose as practical. Terse variable names such as "$i" and "$n" are discouraged for anything other than the smallest loop contexts. If a loop contains more than 20 lines of code, variables for such indices or counters need to have more descriptive names.
Constants may contain both alphanumeric characters and the underscore. Numbers are permitted in constant names.
Constant names must always have all letters capitalized.
To enhance readability, words in constant names must be separated by underscore characters. For example, "EMBED_SUPPRESS_EMBED_EXCEPTION" is permitted but "EMBED_SUPPRESSEMBEDEXCEPTION" is not.
Constants must be defined as class members by using the "const" construct. Defining constants in the global scope with "define" is permitted but discouraged.
Unlike PHP's documentation, the Zend Framework uses lowercase for both boolean values and the "null" value.
Usage of the global keyword is not allowed. Use $GLOBALS[xxx] instead.
Actually we are writing automatted tests for Zend Framework. All tests are in sum a defined coding standard for Zend Framework using PHP_CodeSniffer and will be delivered with Zend Framework in the future.
These tests are called "Sniffs" and include the following:
- ClassFileNameSniff: Tests that the file name and the name of the class contained within the file match
- LowercaseClassKeywordsSniff: Ensures all class keywords are lowercase
- InlineCommentSniff: Checks that no perl-style comments (#)are used
- ElseIfDeclarationSniff: Verifies that there are not elseif statements. The else and the if should be separated by a space
- ForLoopDeclarationSniff: Verifies that there is a space between each condition of for loops
- ForEachLoopDeclarationSniff: Verifies that there is a space between each condition of foreach loops
- LowercaseDeclarationSniff: Ensures all control structure keywords are lowercase
- SwitchDeclarationSniff: Ensures all the breaks and cases are aligned correctly according to their parent switch's alignment and enforces other switch formatting
- ClosingTagSniff: Checks that the file does not include a closing tag wether at file end nor inline for output purposes
- LineLengthSniff: Checks all lines in the file, and throws warnings if they are over 80 characters in length and errors if they are over 120
- LineEndingsSniff: Checks for Unix (\n) linetermination, disallowing Windows (\r\n) or Max (\r)
- MultipleStatementAlignSniff: Checks alignment of assignments. If there are multiple adjacent assignments, it will check that the equals signs of each assignment are aligned. It will display a warning to advise that the signs should be aligned
- GlobalFunctionSniff: Tests for functions outside of classes
- LowercaseKeywordsSniff: Ensures all class keywords are lowercase
- OpeningFunctionBraceSniff: Checks that the opening brace of a function is on the line after the function declaration
- LowerCaseConstantSniff: Checks that all uses of 'true', 'false' and 'null' are lowercase
- UpperCaseConstantNameSniff: Ensures that constant names are all uppercase
- ValidClassNameSniff: Ensures class and interface names start with a capital letter and use _ separators
- IncrementDecrementUsageSniff: Tests that the ++ operators are used when possible
- DisallowObEndFlushSniff: Disallow ob_end_flush, use ob_get_contents() and ob_end_clean() instead
- DisallowShortOpenTagSniff: Makes sure that shorthand PHP open tags are not used ("<?"), but allows open tag with echo ("<?="). short_open_tag must be set to true for this test to work
- ForbiddenFunctionsSniff: Discourages the use of alias functions that are kept in PHP for compatibility with older versions. Can be used to forbid the use of any function
- GlobalKeywordSniff: Stops the usage of the "global" keyword
- NonExecutableCodeSniff: Warns about code that can never been executed. This happens when a function returns before the code, or a break ends execution of a statement etc
- EchoedStringsSniff: Makes sure that any strings that are "echoed" are not enclosed in brackets like a function call
- DisallowTabSniff: Checks if tabs are used and errors if any are found
- LanguageConstructSpacingSniff: Ensures all language constructs (without brackets) contain a single space between themselves and their content
- SemicolonSpacingSniff: Ensure there is no whitespace before a semicolon
Feel free to mention tests that should be added...