- Zend Framework 2 Coding Standards
- PHP File Formatting
- Naming Conventions
- Abstract Classes
- Functions and Methods
- Coding Style
- PHP Code Demarcation
- String Literals
- String Literals Containing Apostrophes
- Variable Substitution
- String Concatenation
- Class Names In Strings
- Functions and Methods
- Control Statements
- Inline Documentation
This document provides guidelines for code formatting and documentation to individuals and teams contributing to Zend Framework. Many developers using Zend Framework have also found these coding standards useful because their code's style remains consistent with all Zend Framework code. It is also worth noting that it requires significant effort to fully specify coding standards.
Sometimes developers consider the establishment of a standard more important than what that standard actually suggests at the most detailed level of design. The guidelines in Zend Framework's coding standards capture practices that have worked well on the Zend Framework project. You may modify these standards or use them as is in accordance with the terms of our license.
Topics covered in Zend Framework's coding standards include:
- PHP File Formatting
- Naming Conventions
- Coding Style
- Inline Documentation
Coding standards are important in any development project, but they are particularly important when many developers are working on the same project. Coding standards help ensure that the code is high quality, has fewer bugs, and can be easily maintained.
This document attempts to follow RFC 2119's verbiage for indicating requirements.
- must and must not indicate non-optional requirements
- should and should not indicate recommendations for which exceptions may exist
- may indicates truly optional requirements
For files that contain only PHP code, the closing tag (?>) must not be used. It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response.
Important: Inclusion of arbitrary binary data as permitted by __HALT_COMPILER() must not be used in PHP files in the Zend Framework project or files derived from them. Use of this feature is only permitted for some installation scripts.
Indentation must consist of 4 spaces. Tabs must not be used for indentation.
The target line length is 80 characters. That is to say, Zend Framework developers should strive keep each line of their code under 80 characters where possible and practical. However, longer lines are acceptable in some circumstances. The maximum length of any line of PHP code is 120 characters.
Line termination follows the Unix text file convention. Lines must end with a single linefeed (LF) character. Linefeed characters are represented as ordinal 10, or hexadecimal 0x0A.
Note: Do not use carriage returns (CR) as is the convention in Apple OS's (0x0D) or the carriage return/linefeed combination (CRLF) as is standard for the Windows OS (0x0D, 0x0A).
Zend Framework standardizes on a class naming convention whereby:
- Namespaces have a 1:1 relationship to the filesystem.
- Classes are stored within the directory determined by the namespace.
The root directory of a library contains a directory named after the top-level namespace; in the case of Zend Framework, the root directory would be "library/", as it contains the "Zend/" directory, which corresponds to the top-level namespace within the Zend Framework distribution.
Namespaces must contain only alphanumeric characters, the underscore, and, of course, the namespace separator ().
Namespaces should be MixedCase, and acronyms used in namespaces should as well. As examples:
- the namespace "Zend\PDF" would not be allowed, while "Zend\Pdf" is acceptable.
- the namespace "Zend\XMLRPC" would not be allowed, while "Zend\XmlRpc" is acceptable.
Underscores in namespaces have no special meaning, and will not be translated to the directory separator.
Code deployed alongside Zend Framework libraries but which is not part of the Zend Framework standard distribution should utilize separate namespaces.
When aliasing within ZF library code, the aliases should typically follow these patterns:
- If aliasing a namespace, use the final segment of the namespace; this can be accomplished by simply omitting the "as" portion of the alias:
- If aliasing a class, either use the class name (no "as" clause), or suffix the class with the subcomponent namespace preceding it:
Class names must contain only alphanumeric characters and the underscore. Numbers are permitted in class names but are discouraged in most cases. Underscores are only permitted in place of the path separator; a class named "Do_Something" would map to the filename "Do/Something.php" (and potentially under a hierarchy named after any
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.
See the class names in the standard and extras libraries for examples of this classname convention.
Abstract classes follow the same conventions as classes, with one additional rule: abstract class names must begin with the term, "Abstract". As examples, "AbstractAdapter" and "AbstractWriter" are both considered valid abstract class names.
Abstract classes should be in the same namespace as concrete implementations. The following would be considered invalid usage:
While the next example displays proper usage:
Interfaces follow the same conventions as classes, with one additional rule: interface must be nouns or adjectives. As examples, "ServiceLocation", "EventCollection", and "PluginLocator" are all considered appropriate interface names.
In many cases, it can be difficult to identify a good name for an interface. As an example, for the EventManager component, the name "EventManager" seemed like a likely candidate for both the gateway class as well as the interface. In cases like these, try and identify the behavior described by the interface; in this particular case, we named the interface "EventCollection", as it described a collection of events and handlers, and the class retained the name of "EventManager" as it was a concrete implementation with actual behaviors that could be called.
All other PHP files must only use alphanumeric characters, underscores, and the dash character ("-"). Spaces are strictly prohibited.
Any file that contains PHP code should end with the extension ".php", with the notable exception of view scripts. The following examples show acceptable filenames for Zend Framework classes:
File names must map to class names as described above.
Function names must contain only 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 "camelCase" formatting.
Verbosity is encouraged. Function names should be as verbose as is practical to fully describe their purpose and behavior.
These are examples of acceptable names for functions:
For object-oriented programming, accessors for instance or static variables should be prefixed with "get" or "set". In implementing design patterns, such as the singleton or factory patterns, the name of the method should contain the pattern name where practical to more thoroughly describe behavior.
For methods on objects that are declared with the "private" or "protected" modifier, the first character of the method name may be an underscore. This is the only acceptable application of an underscore in a method name, and is discouraged (as it makes refactoring to public visibility more difficult). Methods declared "public" should not contain an underscore.
Functions in the global scope (a.k.a "floating functions") may be used, but are discouraged. Consider wrapping these functions in a static class, or within a specific namespace.
Variable names must contain only alphanumeric characters. Underscores are not permitted. Numbers are permitted in variable names but are discouraged in most cases.
For variables that are declared with private or protected visibility, the first character of the variable name may be a single underscore. This is the only acceptable application of an underscore in a variable name, and is discouraged (as it makes refactoring to public visibility more difficult). Member variables declared with public visibility *should not* start with an underscore.
As with function names, variable names must always start with a lowercase letter and follow the "camelCaps" capitalization convention.
Verbosity is encouraged. Variables should always be as verbose as practical to describe the data that the developer intends to store in them. Terse variable names such as "$i" and "$n" are discouraged for all but the smallest loop contexts. If a loop contains more than 20 lines of code, the index variables should have more descriptive names.
Constant names may contain both alphanumeric characters and underscores.
All letters used in a constant name must be capitalized, while all words in a constant name 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 with the "const" modifier. Constants may be defined in the global scope or within namespaces.
PHP code must always be delimited by the full-form, standard PHP tags:
The closing PHP tag (?>) must be omitted if no markup or code follows it.
Short tags must not be used within Zend Framework library code, but may be used within view scripts.
When a string is literal (contains no variable substitutions), the apostrophe or "single quote" should be used to demarcate the string:
When a literal string itself contains apostrophes, you may demarcate the string with quotation marks or "double quotes". This is especially useful for SQL statements:
This syntax is preferred over escaping apostrophes as it is much easier to read.
Variable substitution should use either of the folowing forms:
For consistency, this form should not be used:
Strings must be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:$company = 'Zend' . ' ' . 'Technologies';
When concatenating strings with the "." operator, one should break the statement into multiple lines to improve readability. In these cases, each successive line should be padded with white space such that the "."; operator is aligned under the "=" operator:
When referencing a class name in a string, the fully qualified class name must be provided, and must not include a preceding namespace separator. As an example, if in the namespace "Zend\Log", and referencing the class "StreamWriter" in the "Writer" subnamespace, you would use the string "Zend\Log\Writer\StreamWriter".
When declaring indexed arrays with the array function, a trailing space must be added after each comma delimiter to improve readability:$sampleArray = array(1, 2, 3, 'Zend', 'Studio');
It is permitted to declare multi-line indexed arrays using the array construct. In this case, each successive line must be padded with spaces such that beginning of each line is aligned:
Alternately, the initial array item may begin on the following line. If so, it must be padded at one indentation level greater than the line containing the array declaration, and all successive lines must have the same indentation; the closing paren must be on a line by itself at the same indentation level as the line containing the array declaration:
When using this latter declaration, you should use a trailing comma for the last item in the array; this minimizes the impact of adding new items on successive lines, and helps to ensure no parse errors occur due to a missing comma.
When declaring associative arrays with the array construct, one should break the statement into multiple lines. In this case, each successive line must be padded with white space such that both the keys and the values are aligned:
Alternately, the initial array item may begin on the following line. If so, it must be padded at one indentation level greater than the line containing the array declaration, and all successive lines must have the same indentation; the closing paren must be on a line by itself at the same indentation level as the line containing the array declaration. For readability, the various "=>" assignment operators should be padded such that they align.
When using this latter declaration, one should use a trailing comma for the last item in the array; this minimizes the impact of adding new items on successive lines, and helps to ensure no parse errors occur due to a missing comma.
Files should contain a single namespace; composing multiple namespaces in a single file is strongly discouraged.
Namespace declarations must be the first statement in a file, unless multiple namespaces are declared; the only code that should precede the declaration should be a file-level documentation block, with a single empty line between the docblock and the namespace declaration.
Namespace declarations done according to the above must not have any indentation.
In the case that multiple namespace declarations must be placed in the same file, such declarations must utilize blocks and not single-line declarations. The opening brace must be placed on the following line at the same level of indentation, and all code within the block must receive an extra level of indentation. For example, the following is invalid:
But the following is correct:
All explicit dependencies used by a class must be imported. These include classes and interfaces used in method typehints and explicit instanceof type checks, classes directly instantiated, etc. Exceptions include:
- Code within the current namespace or subnamespaces of the current namespace
- Class names that are dynamically resolved (e.g., from a plugin broker)
Import statements must be declared once, at the top of the file, following the namespace declaration. The use statement should be issued once, with one class (and optional alias) per line, separated by commas and terminated on the last import by a semicolon; class names should be aligned:
Classes must be named according to Zend Framework's naming conventions.
The brace must be written on the line underneath the class name, at the same level of indentation as the class declaration.
Every class must have a documentation block that conforms to the PHPDocumentor standard.
All code in a class must be indented with four spaces additional to the level of indentation of the class declaration.
PHP files declaring classes must contain a single PHP class only.
Placing additional code in class files may be done, but is discouraged. In such files, two blank lines must separate the class from any additional PHP code in the class file.
The following is an example of an acceptable class declaration:
Classes that extend other classes or which implement interfaces should declare their dependencies on the same line when possible.
If as a result of such declarations, the line length exceeds the maximum line length, break the line before the extends and/or implements keywords, and pad those lines by one indentation level.
If the class implements multiple interfaces and the declaration exceeds the maximum line length, break after each comma separating the interfaces, and indent the interface names such that they align.
Member variables must be named according to Zend Framework's variable naming conventions.
Any variables declared in a class must be listed at the top of the class, above the declaration of any methods.
The var construct must not be used. Member variables must declare their visibility by using one of the private, protected, or public visibility modifiers. Giving access to member variables directly by declaring them as public may be done, bug is discouraged in favor of accessor methods (set & get).
Functions must be named according to Zend Framework's function naming conventions.
Methods inside classes must always declare their visibility by using one of the private, protected, or public visibility modifiers.
As with classes, the brace must always be written on the line underneath the function name. Space must not be inserted between the function name and the opening parenthesis for the arguments.
Functions *should not* be declared in the global scope.
The following is an example of an acceptable function declaration in a class:
In cases where the argument list exceeds the maximum line length, you may introduce line breaks. Additional arguments to the function or method must be indented one additional level beyond the function or method declaration. A line break must occur before the closing argument paren, which must be placed on the same line as the opening brace of the function or method with one space separating the two, and at the same indentation level as the function or method declaration. The following is an example of one such situation:
Pass-by-reference is the only parameter passing mechanism permitted in a method declaration.
Call-time pass-by-reference must not be used.
The return value must not be enclosed in parentheses. This can hinder readability, in addition to breaking code if a method is later changed to return by reference.
Function arguments must be separated by a single trailing space after the comma delimiter. The following is an example of an acceptable invocation of a function that takes three arguments:threeArguments(1, 2, 3);
Call-time pass-by-reference must not be used. See the function declarations section for the proper way to pass function arguments by-reference.
In passing arrays as arguments to a function, the function call may include the array declaration and may be split into multiple lines to improve readability. In such cases, the normal guidelines for writing arrays still apply:
Control statements based on the if and elseif constructs must have a single space before the opening parenthesis of the conditional and a single space after the closing parenthesis.
Within the conditional statements between the parentheses, operators must be separated by spaces for readability. Inner parentheses should be used to improve logical grouping for larger conditional expressions.
The opening brace must be written on the same line as the conditional statement. The closing brace must be written on its own line. Any content within the braces must be indented using four spaces.
If the conditional statement causes the line length to exceed the maximum line length and has several clauses, you may break the conditional into multiple lines. In such a case, break the line prior to a logic operator, and pad the line such that it aligns under the first character of the conditional clause. The closing paren in the conditional will then be placed on a line with the opening brace, with one space separating the two, at an indentation level equivalent to the opening control statement.
The intention of this latter declaration format is to prevent issues when adding or removing clauses from the conditional during later revisions.
For if statements that include elseif or else, the formatting conventions are similar to the if construct. The following examples demonstrate proper formatting for if statements with else and/or elseif constructs:
PHP allows statements to be written without braces in some circumstances. This coding standard makes no differentiation; all if, elseif or else statements must use braces.
Control statements written with the switch statement must have a single space before the opening parenthesis of the conditional statement and after the closing parenthesis.
All content within the switch statement must be indented using four spaces. Content under each case statement must be indented using an additional four spaces.
The construct default should not be omitted from a switch statement.
It is sometimes useful to write a case statement which falls through to the next case by not including a break or return within that case. To distinguish these cases from bugs, any case statement where break or return are omitted must contain a comment indicating that the break was intentionally omitted.
All documentation blocks ("docblocks") must be compatible with the phpDocumentor format. Describing the phpDocumentor format is beyond the scope of this document. For more information, visit: PHPDoc
All class files must contain a "file-level" docblock at the top of each file and a "class-level" docblock immediately above each class. Examples of such docblocks can be found below.
Classes and interfaces referenced by annotations must follow the same resolution order as PHP. In other words:
- If the class is in the same namespace, simply refer to the class name without the namespace:
- If the class is in a subnamespace of the current namespace, refer to it relative to the current namespace:
- If the class is imported, either via a namespace or explicit class name, use the name as specified by the import:
- If the class is from another namespace, but not explicitly imported, provide a globally resolvable name:namespace Foo\Component;
This last case should rarely happen, primarily since you should be importing any dependencies. One case where it may happen, however, is in @return annotations, as return types might be determined outside the class scope.
Every file that contains PHP code must have a docblock at the top of the file that contains these phpDocumentor tags at a minimum:
The @category annotation must have a value of "Zend".
The @package annotation must be assigned, and should be equivalent to the component name of the class contained in the file; typically, this will only have two segments, the "Zend" prefix, and the component name.
The @subpackage annotation is optional. If provided, it should be the subcomponent name, minus the class prefix. In the example above, the assumption is that the class in the file is either "Zend_Magic_Wand", or uses that classname as part of its prefix.
Every class must have a docblock that contains these phpDocumentor tags at a minimum:
The @category annotation must have a value of "Zend".
The @package annotation must be assigned, and should be equivalent to the component to which the class belongs; typically, this will only have two segments, the "Zend" prefix, and the component name.
The @subpackage annotation is optional. If provided, it should be the subcomponent name, minus the class prefix. In the example above, the assumption is that the class described is either "Zend_Magic_Wand", or uses that classname as part of its prefix.
Every function, including object methods, must have a docblock that contains at a minimum:
- A description of the function
- All of the arguments
- All of the possible return values
It is not necessary to use the @access annotation because the access level is already known from the public, private, or protected visibility modifier used to declare the function.
If a function or method may throw an exception, use @throws for all known exception classes: