Code style specification This specification is the inheritance and extension of [PSR-1] [] basic code specification. This specification aims to develop a series of standardized php code rules to reduce the inconvenience caused by different code styles when browsing code of different authors. When multiple programmers cooperate in multiple projects, a common coding specification is required, The style norms in this article are derived from the common characteristics of different project code styles, Therefore, the value of this specification lies in that we all follow this encoding style, not in itself. Key words: "MUST" ("MUST"), "must not/must not" ("must not"), "need" ("REQUIRED "), "Will" ("SHALL"), "will NOT" ("shall not"), "SHOULD" ("shocould"), "shouldn't" ("shocould NOT "), For detailed descriptions of "recommendations" ("RECOMMENDED"), "Yes" ("MAY"), and "OPTIONAL" ("OPTIONAL"), see [RFC 2119] []. Overview CodeRequiredComplies with the encoding specification in [PSR-1. CodeRequiredUse four space characters instead of the tab key for indentation. Characters per lineShouldThe flexibility is kept within 80, theoreticallyMust notMore than 120,Certainly notThere are hard limitations. After each namespace declaration statement and use declaration statement block,RequiredInsert a blank row. Class start curly braces ({)RequiredWrite the statement into a row after the function declaration, and end the curly braces (}).RequiredWrite it into a row after the function body. METHOD Start curly braces ({)RequiredWrite the statement into a row after the function declaration, and end the curly braces (}).RequiredWrite it into a row after the function body. Class attributes and methodsRequiredAdd access modifiers (private, protected, and public), abstract, and finalRequiredBefore the access modifierRequiredAfter the access modifier is declared. After the keyword of the control structureRequiredThere must be a space character, and when a method or function is calledCertainly notYes. Start curly braces ({) of the control structure ({)RequiredWrite the statement in the same row and end the curly braces (})RequiredWrite it into a row after the subject. The start and end brackets of the control structure are bothCertainly notThere is a space character. 1.1. exampleThe following example shows most of the above specifications:
- Namespace Vendor \ Package;
- Use FooInterface;
- Use BarClass as Bar;
- Use OtherVendor \ OtherPackage \ BazClass;
- Class Foo extends Bar implements FooInterface
- {
- Public function sampleFunction ($ a, $ B = null)
- {
- If ($ a ===$ B ){
- Bar ();
- } Elseif ($ a> $ B ){
- $ Foo-> bar ($ arg1 );
- } Else {
- BazClass: bar ($ arg2, $ arg3 );
- }
- }
- Final public static function bar ()
- {
- // Method body
- }
- }
General rules 2.1 Basic coding principlesCodeRequiredComplies with all specifications in [PSR-1. 2.2 filesAll php filesRequiredUse Unix LF (linefeed) as the row Terminator. All php filesRequiredEnd with a blank line. PHP code filesRequiredOmitting the last?> End tag. 2.3. rowsRow lengthCertainly notThere are hard constraints. Soft length constraintsYesThe length must be less than 120 characters. if the length is exceeded, the editor with code specification checkYesWarning,Must notSend an error message. Each lineNoRows with more than 80 characters and more than 80 charactersShouldFold to multiple rows. After non-empty rowsCertainly notThere are extra space characters. Empty rowYesThis makes it easier to read the code and helps block the code. Each lineCertainly notMore than one statement exists. 2.4. indentCodeRequiredIndent with four space characters,Certainly notUse the tab key. Note: the advantages of using spaces instead of tab indentation are, Avoid confusion when comparing code differences, patching, rereading code, and comments. In addition, space indentation makes alignment more convenient. 2.5. keyword and True/False/NullPHP all [keywords] []RequiredAll lowercase letters. Constants true, false, and null are alsoRequiredAll lowercase letters. Namespace and use declaration A blank row must be inserted after namespace is declared. All use must be declared after namespace. Each use statement must have only one use keyword. A blank line is required after the use statement block is declared. For example:
- Namespace Vendor \ Package;
- Use FooClass;
- Use BarClass as Bar;
- Use OtherVendor \ OtherPackage \ BazClass;
- //... Additional PHP code...
Classes, attributes, and methods The "class" here refers to all class classes, interfaces, and traits reusable code blocks. 4.1. expansion and inheritanceKeywords: extends and implementsRequiredWritten in the same row of the class name. Class start curly bracketsRequiredExclusive row, ending curly bracketsRequiredExclusive row after the class subject.
- Namespace Vendor \ Package;
- Use FooClass;
- Use BarClass as Bar;
- Use OtherVendor \ OtherPackage \ BazClass;
- Class ClassName extends ParentClass implements \ ArrayAccess, \ Countable
- {
- // Constants, properties, methods
- }
The inheritance list of implements is alsoYesDivided into multiple rows. in this way, each inherited interface name isRequiredSeparate independent rows, including the first one.
- Namespace Vendor \ Package;
- Use FooClass;
- Use BarClass as Bar;
- Use OtherVendor \ OtherPackage \ BazClass;
- Class ClassName extends ParentClass implements
- \ ArrayAccess,
- \ Countable,
- \ Serializable
- {
- // Constants, properties, methods
- }
4.2. attributesEach attribute hasRequiredAdd an access modifier. Must notUse the keyword var to declare an attribute. Each statementMust notMore than one attribute is defined. NoUse underscores (_) as the prefix to distinguish between protected and private attributes. The following is an example of attribute declaration:
- Namespace Vendor \ Package;
- Class ClassName
- {
- Public $ foo = null;
- }
4.3. methodAll methodsRequiredAdd an access modifier. NoUse an underscore as the prefix to distinguish between protected and private. After method nameCertainly notThere is a space character, which starts with curly bracketsRequiredExclusive row, ending curly bracketsRequiredSeparate a row after the method subject. The left and right brackets of the parameterCertainly notThere are spaces. For a standard method declaration, refer to the following example to see the brackets, commas, spaces, and brackets.
- Namespace Vendor \ Package;
- Class ClassName
- {
- Public function fooBarBaz ($ arg1, & $ arg2, $ arg3 = [])
- {
- // Method body
- }
- }
4.4. method parametersIn the parameter list, after each commaRequiredThere must be a space before the commaCertainly notThere are spaces. Parameters with default values,RequiredPut it at the end of the parameter list.
- Namespace Vendor \ Package;
- Class ClassName
- {
- Public function foo ($ arg1, & $ arg2, $ arg3 = [])
- {
- // Method body
- }
- }
Parameter listYesIn this way, each parameter, including the first parameter, is divided into multiple rows.RequiredSeparate rows. After the parameter list is split into multiple rows, ending brackets and METHOD Start curly braces must be written in the same row, separated by a space in the middle.
- Namespace Vendor \ Package;
- Class ClassName
- {
- Public function aVeryLongMethodName (
- ClassTypeHint $ arg1,
- & $ Arg2,
- Array $ arg3 = []
- ){
- // Method body
- }
- }
4.5. abstract, final, and staticWhen you need to add abstract or final declarations,RequiredBefore the access modifier, while staticRequiredWrite it after it.
- Namespace Vendor \ Package;
- Abstract class ClassName
- {
- Protected static $ foo;
- Abstract protected function zim ();
- Final public static function bar ()
- {
- // Method body
- }
- }
4.6. call methods and functionsMethod or function name and parameter left bracketsCertainly notThere is a space, and the parameter is also in front of the right bracketCertainly notThere are spaces. Before each parameterCertainly notThere are spaces, but the followingRequiredThere is a space.
- Bar ();
- $ Foo-> bar ($ arg1 );
- Foo: bar ($ arg2, $ arg3 );
ParametersYesInto multiple rows. each parameter, including the first parameter, isRequiredSeparate rows.
- $ Foo-> bar (
- $ LongArgument,
- $ LongerArgument,
- $ MuchLongerArgument
- );
Control Structure The basic specification of the control structure is as follows: After controlling structure keywordsRequiredThere is a space. Left Parenthesis (rearCertainly notThere are spaces. Right brackets ).Certainly notSpace is allowed. Right parenthesis) and start curly braces {YesThere is a space. BodyYesOne indent is required. Ending curly braces}YesSeparate the line after the struct body. The body of each struct isRequiredIncluded in pair curly brackets, This makes the struct more structured and reduces the possibility of errors when new rows are added. 5.1. if, elseif, and elseThe standard if structure is shown in the following code. pay attention to the brackets, spaces, and brackets, Note that both else and elseif are in the same line as the ending curly braces.
- If ($ expr1 ){
- // If body
- } Elseif ($ expr2 ){
- // Elseif body
- } Else {
- // Else body;
- }
ShouldUse the keyword elseif instead of all else if to make all the control keywords look like a separate word. 5.2. switch and caseThe following code shows the standard switch structure. pay attention to the brackets, spaces, and brackets. Case StatementRequiredOne indentation is performed relative to the switch, while the break statement and other statements in the case must all be indented relative to the case. If a non-empty case-based direct statement exists, a comment similar to // no break must exist in the subject.
- Switch ($ expr ){
- Case 0:
- Echo 'first case, with a break ';
- Break;
- Case 1:
- Echo 'second case, which falls through ';
- // No break
- Case 2:
- Case 3:
- Case 4:
- Echo 'third case, return instead of Break ';
- Return;
- Default:
- Echo 'default case ';
- Break;
- }
5.3. while and do whileA standard while statement should be as follows. pay attention to its parentheses, spaces, and brackets.
- While ($ expr ){
- // Structure body
- }
The standard do while statement is as follows. Similarly, pay attention to the brackets, spaces, and brackets.
- Do {
- // Structure body;
- } While ($ expr );
5.4.The standard for statement is as follows. pay attention to the brackets, spaces, and brackets.
- For ($ I = 0; $ I <10; $ I ++ ){
- // For body
- }
5.5. foreachThe standard foreach statement is as follows. pay attention to the brackets, spaces, and brackets.
- Foreach ($ iterable as $ key => $ value ){
- // Foreach body
- }
5.6. try, catchThe standard try catch statement is as follows. pay attention to the brackets, spaces, and brackets.
- Try {
- // Try body
- } Catch (FirstExceptionType $ e ){
- // Catch body
- } Catch (OtherExceptionType $ e ){
- // Catch body
- }
Closure When the closure is declared, the keywords after function and before and after the keyword use are bothRequiredThere must be a space. Start curly bracketsRequiredWrite the statement in the same row and end the curly braces.RequiredThe next line that follows the end of the subject. The left and right brackets of the parameter list and variable list,Must notThere are spaces. In the list of parameters and variablesMust notThere is a space, and after a commaRequiredA space is required. Parameters with default values in the closureRequiredPut it behind the list. The standard closure declaration statement is as follows. Note the brackets, commas, spaces, and brackets.
- $ ClosureWithArgs = function ($ arg1, $ arg2 ){
- // Body
- };
- $ ClosureWithArgsAndVars = function ($ arg1, $ arg2) use ($ var1, $ var2 ){
- // Body
- };
Parameter list and variable listYesDivided into multiple rows. in this way, every parameter or variable, including the first one, isRequiredSeparate rows, and the right parenthesis of the list and the start curly braces of the closureRequiredPut it in the same row. The following example contains multiple cases where the parameter and variable list are divided into multiple rows.
- $ LongArgs_noVars = function (
- $ LongArgument,
- $ LongerArgument,
- $ MuchLongerArgument
- ){
- // Body
- };
- $ NoArgs_longVars = function () use (
- $ LongVar1,
- $ LongerVar2,
- $ MuchLongerVar3
- ){
- // Body
- };
- $ LongArgs_longVars = function (
- $ LongArgument,
- $ LongerArgument,
- $ MuchLongerArgument
- ) Use (
- $ LongVar1,
- $ LongerVar2,
- $ MuchLongerVar3
- ){
- // Body
- };
- $ LongArgs_shortVars = function (
- $ LongArgument,
- $ LongerArgument,
- $ MuchLongerArgument
- ) Use ($ var1 ){
- // Body
- };
- $ ShortArgs_longVars = function ($ arg) use (
- $ LongVar1,
- $ LongerVar2,
- $ MuchLongerVar3
- ){
- // Body
- };
Note: When the closure is directly used as a parameter for function or method call, the above rules still apply.
- $ Foo-> bar (
- $ Arg1,
- Function ($ arg2) use ($ var1 ){
- // Body
- },
- $ Arg3
- );
Summary The above specifications are inevitably neglected, including but not limited: Definitions of global variables and constants Function definition Operators and assignments Intra-row alignment Comments and document description blocks Class name prefix and suffix Best practices The amendment and extension after this provision will make up for the above shortcomings. Appendix A. questionnaire surveyIn order to develop this specification, the group has developed a questionnaire to count the common standards of member projects. The following are the data of this survey, which is for reference here. A.1. questionnaire data
- Url, http://www.horde.org/apps/horde/docs/CODING_STANDARDS,http://pear.php.net/manual/en/standards.php,http://solarphp.com/manual/appendix-standards.style,http://framework.zend.com/manual/en/coding-standard.html,http://symfony.com/doc/2.0/contributing/code/standards.html,http://www.ppi.io/docs/coding-standards.html,https://github.com/ezsystems/ezp-next/wiki/codingstandards,http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html,https://github.com/UnionOfRAD/lithium/wiki/Spec%3A-Coding,http://drupal.org/coding-standards,http://code.google.com/p/sabredav/,http://area51.phpbb.com/docs/31x/coding-guidelines.html,https://docs.google.com/a/zikula.org/document/edit?authkey=CPCU0Us&hgd=1&id=1fcqb93Sn-hR9c0mkN6m_tyWnmEvoswKBtSc0tKkZmJA,http://www.chisimba.com,n/a,https://github.com/Respect/project-info/blob/master/coding-standards-sample.php,n/a,Object Calisthenics for PHP, http://doc.nette.org/en/coding-standard,http://flow3.typo3.org,https://github.com/propelorm/Propel2/wiki/Coding-Standards,http://developer.joomla.org/coding-standards.html
- Voting, yes, no, no ,?, Yes, no, yes
- Indent_type, 4, 4, 4, 4, tab, 4, tab, tab, 2, 4, 4, 4, 4, 4, tab, tab, 4, tab
- Line_length_limit_soft, 75, 75, 75, no, 85,120,120, 80, 80, 80, no, 80 ,?,?, 120, 80, 150, no
- Line_length_limit_hard, 85, 85, 85, 85, no, 100 ,?, No, 100,100 ,?, 120,120, no
- Example, studly, example, example, lower, studly ,?, Studly, studly, studly
- Class_brace_line, next, same, next, same, next, same, next, next
- Constant_names, upper, upper, upper, upper
- True_false_null, lower, upper, lower, lower
- Method_names, camel, lower_under, camel, camel, camel, camel
- Method_brace_line, next, same, next, same, next, next
- Control_brace_line, same, next, same, next, same, same, same, next
- Control_space_after, yes, no, yes, yes, yes, yes, yes
- Always_use_control_braces, yes, no, yes, yes, yes, yes
- Else_elseif_line, same, next, same, same, next, next, same, same, same, next
- Case_break_indent_from_switch, 0/1, 0/1, 0/1, 1/2, 1/2, 1/2, 1/2, 1/1, 1/1, 1/2, 1/2, 1/1, 1/2, 1/2, 1/2, 1/2, 1/2, 1/2, 0/1, 1/1, 1/2, 1/2
- Function_space_after, no, no, no, no
- Closing_php_tag_required, no, yes, yes, no, yes, no, no
- Line_endings, LF ,?, LF ,?, LF ,?,, LF ,?, LF, LF, LF
- Static_or_visibility_first, static ,?, Static, either, visibility, either, static, either ,?, Visibility ,?,?, Either, either, visibility, visibility, static ,?
- Control_space_parens, no, yes, no, yes ,?, No, no
- Blank_line_after_php, no, yes, yes, no, yes, yes, no, yes ,?, Yes, yes, no
- Class_method_control_brace, next/same, next/same, same/same, next/next, same/same, next/next, next/same, next/same, next/next, next/same, next/same, next/same, same/same, next/same, next/next
A.2. questionnaire descriptionIndent_type: Indent type. tab = "use the tab key once", 2 or 4 = "number of spaces" Line_length_limit_soft: "Soft" limit on the number of characters in each line .? = No. no indicates no limit. Line_length_limit_hard: The "hard" limit on the number of characters in each line .? = No. no indicates no limit. Class_names: Name of the class name. lower = only lower-case letters are allowed, lower_under = lower-case letters separated by slide lines, and studly = StudlyCase's hump style. Class_brace_line: Is the starting curly braces of a class the same line as the class keyword or the next line? Constant_names: How do I name constants of a class? Upper = uppercase letters separated by underscores. True_false_null: Are the keywords true, false, and null all lower case lower or all upper case upper? Method_names: How do I name a method? Camel = camelCase, lower_under = lowercase letters separated by underlines. Method_brace_line: Is the start curly braces of the method the same line as the method name or the next line? Control_brace_line: Is the starting curly braces of the control structure the same line as the declaration or the next line? Control_space_after: Is there a space after the control structure keyword? Always_use_control_braces: Should control struct be included in curly brackets? Else_elseif_line: Is the else or elseif in the same row with the ending curly braces or in the next row? Case_break_indent_from_switch: How many times does the case and break in the switch statement need to be indented relative to the switch? Function_space_after: In a function call statement, is there a space between the function name and the left parenthesis of the variable list? Closing_php_tag_required: Is it required for files with pure PHP code?> End tag? Line_endings: Which type of row Terminator is selected? Static_or_visibility_first: When declaring a static method, is static before or after the access modifier? Control_space_parens: In the control structure, are there spaces between the left and the right brackets? Yes = if ($ expr), no = if ($ expr ). Blank_line_after_php: Does PHP need a blank line after the tag is started? Class_method_control_brace: Start the curly braces in the class, method, and control structure position statistics. A.3. questionnaire statistics
- Indent_type:
- Tab: 7
- 2: 1
- 4: 14
- Line_length_limit_soft:
- ? : 2
- No: 3
- 75: 4
- 80: 6
- 85: 1
- 100: 1
- 120: 4
- 150: 1
- Line_length_limit_hard:
- ? : 2
- No: 11
- 85: 4
- 100: 3
- 120: 2
- Class_names:
- ? : 1
- Lower: 1
- Lower_under: 1
- Studly: 19
- Class_brace_line:
- Next: 16
- Same: 6
- Constant_names:
- Upper: 22
- True_false_null:
- Lower: 19
- Upper: 3
- Method_names:
- Camel: 21
- Lower_under: 1
- Method_brace_line:
- Next: 15
- Same: 7
- Control_brace_line:
- Next: 4
- Same: 18
- Control_space_after:
- No: 2
- Yes: 20
- Always_use_control_braces:
- No: 3
- Yes: 19
- Else_elseif_line:
- Next: 6
- Same: 16
- Case_break_indent_from_switch:
- 0/1: 4
- 1/1: 4
- December 14, 1/2
- Function_space_after:
- No: 22
- Closing_php_tag_required:
- No: 19
- Yes: 3
- Line_endings:
- ? : 5
- LF: 17
- Static_or_visibility_first:
- ? : 5
- Either: 7
- Static: 4
- Visibility: 6
- Control_space_parens:
- ? : 1
- No: 19
- Yes: 2
- Blank_line_after_php:
- ? : 1
- No: 13
- Yes: 8
- Class_method_control_brace:
- Next/next: 4
- Next/same: 11
- Next/same: 1
- Same/same: 6
|