PHPPSR-2 code style specification

Source: Internet
Author: User
Tags try catch
PHPPSR-2 code style specification
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. example

The following example shows most of the above specifications:

  1. Namespace Vendor \ Package;
  2. Use FooInterface;
  3. Use BarClass as Bar;
  4. Use OtherVendor \ OtherPackage \ BazClass;
  5. Class Foo extends Bar implements FooInterface
  6. {
  7. Public function sampleFunction ($ a, $ B = null)
  8. {
  9. If ($ a ===$ B ){
  10. Bar ();
  11. } Elseif ($ a> $ B ){
  12. $ Foo-> bar ($ arg1 );
  13. } Else {
  14. BazClass: bar ($ arg2, $ arg3 );
  15. }
  16. }
  17. Final public static function bar ()
  18. {
  19. // Method body
  20. }
  21. }

General rules

2.1 Basic coding principles

CodeRequiredComplies with all specifications in [PSR-1.

2.2 files

All 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. rows

Row 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. indent

CodeRequiredIndent 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/Null

PHP 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:

  1. Namespace Vendor \ Package;
  2. Use FooClass;
  3. Use BarClass as Bar;
  4. Use OtherVendor \ OtherPackage \ BazClass;
  5. //... 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 inheritance

Keywords: extends and implementsRequiredWritten in the same row of the class name.

Class start curly bracketsRequiredExclusive row, ending curly bracketsRequiredExclusive row after the class subject.

  1. Namespace Vendor \ Package;
  2. Use FooClass;
  3. Use BarClass as Bar;
  4. Use OtherVendor \ OtherPackage \ BazClass;
  5. Class ClassName extends ParentClass implements \ ArrayAccess, \ Countable
  6. {
  7. // Constants, properties, methods
  8. }

The inheritance list of implements is alsoYesDivided into multiple rows. in this way, each inherited interface name isRequiredSeparate independent rows, including the first one.

  1. Namespace Vendor \ Package;
  2. Use FooClass;
  3. Use BarClass as Bar;
  4. Use OtherVendor \ OtherPackage \ BazClass;
  5. Class ClassName extends ParentClass implements
  6. \ ArrayAccess,
  7. \ Countable,
  8. \ Serializable
  9. {
  10. // Constants, properties, methods
  11. }

4.2. attributes

Each 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:

  1. Namespace Vendor \ Package;
  2. Class ClassName
  3. {
  4. Public $ foo = null;
  5. }

4.3. method

All 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.

  1. Namespace Vendor \ Package;
  2. Class ClassName
  3. {
  4. Public function fooBarBaz ($ arg1, & $ arg2, $ arg3 = [])
  5. {
  6. // Method body
  7. }
  8. }

4.4. method parameters

In 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.

  1. Namespace Vendor \ Package;
  2. Class ClassName
  3. {
  4. Public function foo ($ arg1, & $ arg2, $ arg3 = [])
  5. {
  6. // Method body
  7. }
  8. }

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.

  1. Namespace Vendor \ Package;
  2. Class ClassName
  3. {
  4. Public function aVeryLongMethodName (
  5. ClassTypeHint $ arg1,
  6. & $ Arg2,
  7. Array $ arg3 = []
  8. ){
  9. // Method body
  10. }
  11. }

4.5. abstract, final, and static

When you need to add abstract or final declarations,RequiredBefore the access modifier, while staticRequiredWrite it after it.

  1. Namespace Vendor \ Package;
  2. Abstract class ClassName
  3. {
  4. Protected static $ foo;
  5. Abstract protected function zim ();
  6. Final public static function bar ()
  7. {
  8. // Method body
  9. }
  10. }

4.6. call methods and functions

Method 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.

  1. Bar ();
  2. $ Foo-> bar ($ arg1 );
  3. Foo: bar ($ arg2, $ arg3 );

ParametersYesInto multiple rows. each parameter, including the first parameter, isRequiredSeparate rows.

  1. $ Foo-> bar (
  2. $ LongArgument,
  3. $ LongerArgument,
  4. $ MuchLongerArgument
  5. );

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 else

The 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.

  1. If ($ expr1 ){
  2. // If body
  3. } Elseif ($ expr2 ){
  4. // Elseif body
  5. } Else {
  6. // Else body;
  7. }

ShouldUse the keyword elseif instead of all else if to make all the control keywords look like a separate word.

5.2. switch and case

The 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.

  1. Switch ($ expr ){
  2. Case 0:
  3. Echo 'first case, with a break ';
  4. Break;
  5. Case 1:
  6. Echo 'second case, which falls through ';
  7. // No break
  8. Case 2:
  9. Case 3:
  10. Case 4:
  11. Echo 'third case, return instead of Break ';
  12. Return;
  13. Default:
  14. Echo 'default case ';
  15. Break;
  16. }

5.3. while and do while

A standard while statement should be as follows. pay attention to its parentheses, spaces, and brackets.

  1. While ($ expr ){
  2. // Structure body
  3. }

The standard do while statement is as follows. Similarly, pay attention to the brackets, spaces, and brackets.

  1. Do {
  2. // Structure body;
  3. } While ($ expr );

5.4.

The standard for statement is as follows. pay attention to the brackets, spaces, and brackets.

  1. For ($ I = 0; $ I <10; $ I ++ ){
  2. // For body
  3. }

5.5. foreach

The standard foreach statement is as follows. pay attention to the brackets, spaces, and brackets.

  1. Foreach ($ iterable as $ key => $ value ){
  2. // Foreach body
  3. }

5.6. try, catch

The standard try catch statement is as follows. pay attention to the brackets, spaces, and brackets.

  1. Try {
  2. // Try body
  3. } Catch (FirstExceptionType $ e ){
  4. // Catch body
  5. } Catch (OtherExceptionType $ e ){
  6. // Catch body
  7. }

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.

  1. $ ClosureWithArgs = function ($ arg1, $ arg2 ){
  2. // Body
  3. };
  4. $ ClosureWithArgsAndVars = function ($ arg1, $ arg2) use ($ var1, $ var2 ){
  5. // Body
  6. };

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.

  1. $ LongArgs_noVars = function (
  2. $ LongArgument,
  3. $ LongerArgument,
  4. $ MuchLongerArgument
  5. ){
  6. // Body
  7. };
  8. $ NoArgs_longVars = function () use (
  9. $ LongVar1,
  10. $ LongerVar2,
  11. $ MuchLongerVar3
  12. ){
  13. // Body
  14. };
  15. $ LongArgs_longVars = function (
  16. $ LongArgument,
  17. $ LongerArgument,
  18. $ MuchLongerArgument
  19. ) Use (
  20. $ LongVar1,
  21. $ LongerVar2,
  22. $ MuchLongerVar3
  23. ){
  24. // Body
  25. };
  26. $ LongArgs_shortVars = function (
  27. $ LongArgument,
  28. $ LongerArgument,
  29. $ MuchLongerArgument
  30. ) Use ($ var1 ){
  31. // Body
  32. };
  33. $ ShortArgs_longVars = function ($ arg) use (
  34. $ LongVar1,
  35. $ LongerVar2,
  36. $ MuchLongerVar3
  37. ){
  38. // Body
  39. };

Note: When the closure is directly used as a parameter for function or method call, the above rules still apply.

  1. $ Foo-> bar (
  2. $ Arg1,
  3. Function ($ arg2) use ($ var1 ){
  4. // Body
  5. },
  6. $ Arg3
  7. );

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 survey

In 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

  1. 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
  2. Voting, yes, no, no ,?, Yes, no, yes
  3. Indent_type, 4, 4, 4, 4, tab, 4, tab, tab, 2, 4, 4, 4, 4, 4, tab, tab, 4, tab
  4. Line_length_limit_soft, 75, 75, 75, no, 85,120,120, 80, 80, 80, no, 80 ,?,?, 120, 80, 150, no
  5. Line_length_limit_hard, 85, 85, 85, 85, no, 100 ,?, No, 100,100 ,?, 120,120, no
  6. Example, studly, example, example, lower, studly ,?, Studly, studly, studly
  7. Class_brace_line, next, same, next, same, next, same, next, next
  8. Constant_names, upper, upper, upper, upper
  9. True_false_null, lower, upper, lower, lower
  10. Method_names, camel, lower_under, camel, camel, camel, camel
  11. Method_brace_line, next, same, next, same, next, next
  12. Control_brace_line, same, next, same, next, same, same, same, next
  13. Control_space_after, yes, no, yes, yes, yes, yes, yes
  14. Always_use_control_braces, yes, no, yes, yes, yes, yes
  15. Else_elseif_line, same, next, same, same, next, next, same, same, same, next
  16. 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
  17. Function_space_after, no, no, no, no
  18. Closing_php_tag_required, no, yes, yes, no, yes, no, no
  19. Line_endings, LF ,?, LF ,?, LF ,?,, LF ,?, LF, LF, LF
  20. Static_or_visibility_first, static ,?, Static, either, visibility, either, static, either ,?, Visibility ,?,?, Either, either, visibility, visibility, static ,?
  21. Control_space_parens, no, yes, no, yes ,?, No, no
  22. Blank_line_after_php, no, yes, yes, no, yes, yes, no, yes ,?, Yes, yes, no
  23. 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 description

Indent_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

  1. Indent_type:
  2. Tab: 7
  3. 2: 1
  4. 4: 14
  5. Line_length_limit_soft:
  6. ? : 2
  7. No: 3
  8. 75: 4
  9. 80: 6
  10. 85: 1
  11. 100: 1
  12. 120: 4
  13. 150: 1
  14. Line_length_limit_hard:
  15. ? : 2
  16. No: 11
  17. 85: 4
  18. 100: 3
  19. 120: 2
  20. Class_names:
  21. ? : 1
  22. Lower: 1
  23. Lower_under: 1
  24. Studly: 19
  25. Class_brace_line:
  26. Next: 16
  27. Same: 6
  28. Constant_names:
  29. Upper: 22
  30. True_false_null:
  31. Lower: 19
  32. Upper: 3
  33. Method_names:
  34. Camel: 21
  35. Lower_under: 1
  36. Method_brace_line:
  37. Next: 15
  38. Same: 7
  39. Control_brace_line:
  40. Next: 4
  41. Same: 18
  42. Control_space_after:
  43. No: 2
  44. Yes: 20
  45. Always_use_control_braces:
  46. No: 3
  47. Yes: 19
  48. Else_elseif_line:
  49. Next: 6
  50. Same: 16
  51. Case_break_indent_from_switch:
  52. 0/1: 4
  53. 1/1: 4
  54. December 14, 1/2
  55. Function_space_after:
  56. No: 22
  57. Closing_php_tag_required:
  58. No: 19
  59. Yes: 3
  60. Line_endings:
  61. ? : 5
  62. LF: 17
  63. Static_or_visibility_first:
  64. ? : 5
  65. Either: 7
  66. Static: 4
  67. Visibility: 6
  68. Control_space_parens:
  69. ? : 1
  70. No: 19
  71. Yes: 2
  72. Blank_line_after_php:
  73. ? : 1
  74. No: 13
  75. Yes: 8
  76. Class_method_control_brace:
  77. Next/next: 4
  78. Next/same: 11
  79. Next/same: 1
  80. Same/same: 6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.