PHP PSR-2 Code Style specification

Source: Internet
Author: User
Tags case statement try catch
Code Style Specification

This specification is the inheritance and extension of the [psr-1][] Basic code specification.

This specification hopes to reduce the inconvenience caused by different code styles when browsing different authors ' code by developing a series of rules for standardizing PHP code.

When multiple programmers work together on multiple projects, a common coding specification is required,
The style specification in this article derives from the common characteristics of many different project code styles,
Therefore, the value of this specification is that we all follow this coding style, not in itself.

Keywords "must" ("must"), "must not/must not be" ("must not"), "Need" ("REQUIRED"),
"Will" ("Shall"), "no" ("Shall not"), "should" ("should"), "shouldn't" ("should not"),
A detailed description of "recommended" ("RECOMMENDED"), "Can" ("may") and "optional" ("OPTIONAL") can be found in [RFC 2119][].

Overview

The code must follow the encoding specification in [psr-1][].

The code must be indented using 4 space characters instead of the TAB key.

The number of characters per line should remain soft within 80, theoretically must not be more than 120, but must not have a hard limit.

After each namespace namespace declaration statement and the use declaration statement block, you must insert a blank line.

The opening curly brace ({) of a class must be written as a line after the function declaration, and the closing curly brace (}) must also be written in a row after the function body.

The opening curly brace ({) of the method must be written in a line after the function declaration, and the closing curly brace (}) must also be written in a row after the function body.

The properties and methods of the class must add access modifiers (private, protected, and public), abstract and final must be declared before the access modifier, and static must Declared after the access modifier.

You must have a space character after the key for the control structure, but you cannot call a method or function.

The opening curly brace ({) of the control structure must be written on the same line as the declaration, and the closing curly brace (}) must be written in a row after the body.

There must be no whitespace at the beginning of the control structure, after the opening parenthesis, and before the closing parenthesis.

1.1. Example

The following example program simply 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 ($arg 1);
    13. } else {
    14. Bazclass::bar ($arg 2, $arg 3);
    15. }
    16. }
    17. Final public static function bar ()
    18. {
    19. Method body
    20. }
    21. }
Copy Code

General clauses

2.1 Basic Coding Guidelines

The code must conform to all specifications in [psr-1][].

2.2 Files

All PHP files must use the Unix LF (linefeed) as the line terminator.

All PHP files must end with a blank line.

The Pure PHP code file must omit the last?> end tag.

2.3. Line

The length of the line must not be rigidly constrained.

Soft length constraints must be limited to 120 characters, if beyond this length, the editor with code specification check must issue a warning, but must not issue an error prompt.

Each line should not be more than 80 characters, and a line greater than 80 characters should be folded into multiple lines.

There must be no extra whitespace after the non-empty line.

Blank lines make it easier to read code and help with the code's chunking.

There must be more than one statement per line.

2.4. Indent

The code must be indented with 4 spaces and must not use the TAB key.

Note: The advantage of using a space instead of the tab indent is that
Avoid confusion when comparing code differences, patching, re-reading code, and commenting.
Also, use a space indent to make alignment easier.

2.5. Keywords and true/false/null

all PHP [keywords] [] must be all lowercase.

Constants True, FALSE, and null must all be lowercase.

namespace and use declarations

A blank line must be inserted after the namespace declaration.

All use must be declared after namespace.

Each use declaration statement must have only one use keyword.

You must have a blank line after the use declaration statement block.

For example:

    1. namespace Vendor\package;
    2. Use Fooclass;
    3. Use Barclass as Bar;
    4. Use Othervendor\otherpackage\bazclass;
    5. ... additional PHP code ...
Copy Code

Classes, properties, and methods

The "class" Here refers to all class classes, interfaces, and traits reusable blocks of code.

4.1. Extensions and Inheritance

Keywords extends and implements must be written on the same line as the class name.

The opening curly brace of a class must be exclusive to one line, and the closing curly brace must also be exclusive on the class body.

    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. }
Copy Code

The Implements inheritance list can also be divided into multiple lines, so that each inherited interface name must be separated into separate 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. }
Copy Code4.2. Properties

Each property must have an access modifier added.

You must not declare a property using the keyword var.

Each statement must not have more than one attribute defined.

do not use underscores as prefixes to differentiate whether the attribute is protected or private.

The following is an example of a property declaration:

    1. namespace Vendor\package;
    2. Class ClassName
    3. {
    4. public $foo = null;
    5. }
Copy Code4.3. Methods

All methods must have an access modifier added.

do not use underscores as prefixes to differentiate whether the method is protected or private.

The method name must not have a space character after it, its opening curly braces have to be exclusive, and the closing curly braces must also be separated into a line after the method body. The argument must not have spaces before the left parenthesis and the closing parenthesis.

A standard method declaration can refer to the following example, paying attention to its parentheses, commas, spaces, and the position of the curly braces.

    1. namespace Vendor\package;
    2. Class ClassName
    3. {
    4. Public Function Foobarbaz ($arg 1, & $arg 2, $arg 3 = [])
    5. {
    6. Method body
    7. }
    8. }
Copy Code4.4. Parameters of the method

In the argument list, you must have a space after each comma, and no space in front of the comma.

Parameters that have default values must be placed at the end of the parameter list.

    1. namespace Vendor\package;
    2. Class ClassName
    3. {
    4. Public Function foo ($arg 1, & $arg 2, $arg 3 = [])
    5. {
    6. Method body
    7. }
    8. }
Copy Code

The parameter list can be broken into multiple rows so that each parameter, including the first parameter, must be taken separately.

After splitting the argument list into multiple rows, the closing parenthesis and the method start curly braces must be written on the same line, separated by a space.

    1. namespace Vendor\package;
    2. Class ClassName
    3. {
    4. Public Function Averylongmethodname (
    5. Classtypehint $arg 1,
    6. & $arg 2,
    7. Array $arg 3 = []
    8. ) {
    9. Method body
    10. }
    11. }
Copy Code4.5. Abstract, final, and static

When an abstract or final declaration needs to be added, it must be written before the access modifier, and static must be written thereafter.

    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. }
Copy Code4.6. Methods and function calls

Method and function call, there must be no space between the method name or the function name and the argument opening parenthesis, and there must be no spaces before the argument closing parenthesis. There must be no space before each parameter, but a space is required thereafter.

    1. Bar ();
    2. $foo->bar ($arg 1);
    3. Foo::bar ($arg 2, $arg 3);
Copy Code

Parameters can be broken into multiple rows, and each parameter, including the first parameter, must be taken separately.

    1. $foo->bar (
    2. $longArgument,
    3. $longerArgument,
    4. $muchLongerArgument
    5. );
Copy Code

Control structure

The basic specifications of the control structure are as follows:

Control structure Keyword must have a space.

Opening parenthesis ( must not have spaces after.)

There must be no spaces before the closing parenthesis.

Closing parenthesis) must have a space between the opening curly braces {.

The body of a struct must be indented once.

Closing curly Brackets} must be in the body of the structure after the individual row.

The body of each struct must be enclosed in pairs of curly braces,
This allows the structure to be more structured and reduces the likelihood of errors when new rows are added.

5.1. If, ElseIf, and Else

The standard if structure is shown in the following code, looking at the brackets, spaces, and the position of the curly braces,
Note that else and ElseIf are all on the same line as the preceding closing curly braces.

    1. if ($expr 1) {
    2. If body
    3. } elseif ($expr 2) {
    4. ElseIf body
    5. } else {
    6. else body;
    7. }
Copy Code

The keyword ElseIf should be used instead of all else if, so that all control keywords are like a single word.

5.2. Switch and case

The standard switch structure is shown in the following code, looking for brackets, spaces, and the position of curly braces.
The case statement must be indented relative to the switch, and the break statement and other statements within the case must be indented relative to the case.
If there is a non-empty case straight-through statement, the body must have a comment like//no break.

    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. }
Copy Code5.3. While and do while

A canonical while statement should look like this, with parentheses, spaces, and the position of curly braces.

    1. while ($expr) {
    2. Structure body
    3. }
Copy Code

The standard do-while statement looks like this, and, again, note the position of the brackets, spaces, and curly braces.

    1. do {
    2. Structure body;
    3. } while ($expr);
Copy Code5.4. For

The standard for statement looks like this, paying attention to its parentheses, spaces, and the position of the curly braces.

    1. for ($i = 0; $i < $i + +) {
    2. For body
    3. }
Copy Code5.5. foreach

The standard foreach statement is as follows, paying attention to its parentheses, spaces, and the position of the curly braces.

    1. foreach ($iterable as $key = = $value) {
    2. foreach Body
    3. }
Copy Code5.6. Try, catch

The standard try Catch statement looks like this, paying attention to its parentheses, spaces, and the position of the curly braces.

    1. try {
    2. Try Body
    3. } catch (Firstexceptiontype $e) {
    4. Catch body
    5. } catch (Otherexceptiontype $e) {
    6. Catch body
    7. }
Copy Code

Closed Package

When you declare a closure, you must have a space after the keyword function and before and after the keyword use.

The opening curly brace must be written on the same line as the declaration, and the closing brace must follow the next line at the end of the body.

There must be no spaces after the left parenthesis of the argument list and the variable list, and before the closing parenthesis.

In the arguments and variables list, there must be no spaces before commas, and spaces must be followed by commas.

Parameters with default values in closures must be placed behind the list.

The standard closure declaration statement is as follows, noting its parentheses, commas, spaces, and the position of the curly braces.

    1. $closureWithArgs = function ($arg 1, $arg 2) {
    2. Body
    3. };
    4. $closureWithArgsAndVars = function ($arg 1, $arg 2) use ($var 1, $var 2) {
    5. Body
    6. };
Copy Code

The argument list and the list of variables can be divided into multiple rows, so that each parameter or variable, including the first one, must be taken separately, and the closing parenthesis of the list must be placed on the same line as the opening brace of the closure.

Here are a few examples of multiple cases where the list of parameters and variables is divided into multiple rows.

  1. $longArgs _novars = function (
  2. $longArgument,
  3. $longerArgument,
  4. $muchLongerArgument
  5. ) {
  6. Body
  7. };
  8. $noArgs _longvars = function () use (
  9. $longVar 1,
  10. $longerVar 2,
  11. $muchLongerVar 3
  12. ) {
  13. Body
  14. };
  15. $longArgs _longvars = function (
  16. $longArgument,
  17. $longerArgument,
  18. $muchLongerArgument
  19. ) Use (
  20. $longVar 1,
  21. $longerVar 2,
  22. $muchLongerVar 3
  23. ) {
  24. Body
  25. };
  26. $longArgs _shortvars = function (
  27. $longArgument,
  28. $longerArgument,
  29. $muchLongerArgument
  30. ) use ($var 1) {
  31. Body
  32. };
  33. $shortArgs _longvars = function ($arg) use (
  34. $longVar 1,
  35. $longerVar 2,
  36. $muchLongerVar 3
  37. ) {
  38. Body
  39. };
Copy Code

Note that the above rules still apply when a closure is used directly as a parameter to a function or method call.

    1. $foo->bar (
    2. $arg 1,
    3. function ($arg 2) use ($var 1) {
    4. Body
    5. },
    6. $arg 3
    7. );
Copy Code

Summarize

The above specifications are inevitably negligent, including but not limited to:

Definition of global variables and constants

Definition of a function

Operators and Assignments

inline alignment

Comments and Document description blocks

prefix and suffix of class name

Best practices

Revisions and extensions after this specification will compensate for these deficiencies.

Appendix A. Questionnaire Survey

In order to prepare the code, the Panel has developed a questionnaire that is used to count the common norms of each member project.
The following is the data for this survey, which is available for review.

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,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,no,no,no,?, Yes,no,yes
  3. Indent_type,4,4,4,4,4,tab,4,tab,tab,2,4,tab,4,4,4,4,4,4,tab,tab,4,tab
  4. line_length_limit_soft,75,75,75,75,no,85,120,120,80,80,80,no,100,80,80,?,?, 120,80,120,no,150
  5. line_length_limit_hard,85,85,85,85,no,no,no,no,100,?, no,no,no,100,100,?, 120,120,no,no,no,no
  6. class_names,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,lower_under,studly, lower,studly,studly,studly,studly,?, studly,studly,studly
  7. Class_brace_line,next,next,next,next,next,same,next,same,same,same,same,next,next,next,next,next,next,next, Next,same,next,next
  8. Constant_names,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper , Upper,upper,upper,upper,upper,upper
  9. True_false_null,lower,lower,lower,lower,lower,lower,lower,lower,lower,upper,lower,lower,lower,upper,lower, Lower,lower,lower,lower,upper,lower,lower
  10. Method_names,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel,lower_under,camel,camel,camel, Camel,camel,camel,camel,camel,camel,camel
  11. Method_brace_line,next,next,next,next,next,same,next,same,same,same,same,next,next,same,next,next,next,next, Next,same,next,next
  12. Control_brace_line,same,same,same,same,same,same,next,same,same,same,same,next,same,same,next,same,same,same, Same,same,same,next
  13. Control_space_after,yes,yes,yes,yes,yes,no,yes,yes,yes,yes,no,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes
  14. Always_use_control_braces,yes,yes,yes,yes,yes,yes,no,yes,yes,yes,no,yes,yes,yes,yes,no,yes,yes,yes,yes,yes,yes
  15. Else_elseif_line,same,same,same,same,same,same,next,same,same,next,same,next,same,next,next,same,same,same, 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,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no
  18. Closing_php_tag_required,no,no,no,no,no,no,no,no,yes,no,no,no,no,yes,no,no,no,no,no,yes,no,no
  19. LINE_ENDINGS,LF,LF,LF,LF,LF,LF,LF,LF,?, LF,?, lf,lf,lf,lf,?,, LF,?, LF,LF,LF
  20. Static_or_visibility_first,static,?, static,either,either,either,visibility,visibility,visibility,either,static , either,?, visibility,?,?, either,either,visibility,visibility,static,?
  21. Control_space_parens,no,no,no,no,no,no,yes,no,no,no,no,no,no,yes,?, No,no,no,no,no,no,no
  22. Blank_line_after_php,no,no,no,no,yes,no,no,no,no,yes,yes,no,no,yes,?, Yes,yes,no,yes,no,yes,no
  23. class_method_control_brace,next/next/same,next/next/same,next/next/same,next/next/same,next/next/same,same/ same/same,next/next/next,same/same/same,same/same/same,same/same/same,same/same/same,next/next/next,next/next/ Same,next/same/same,next/next/next,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same, Next/next/same,next/next/next
Copy CodeA.2. Questionnaire description

Indent_type:
The indentation type. tab = "Use Tab key Once", 2 or 4 = "Number of spaces"

Line_length_limit_soft:
The "soft" limit for the number of characters per line. ? = Non-argument or no answer, no means no limit.

Line_length_limit_hard:
The "hard" limit for the number of characters per line. ? = Non-argument or no answer, no means no limit.

Class_names:
The naming of the class name. lower = only lowercase letters are allowed, Lower_under = lower-case letters, studly = Studlycase hump style.

Class_brace_line:
The opening curly brace of a class is in the same line as the Class keyword or on its next line?

Constant_names:
How are the constants of the class named? Upper = uppercase letters separated by underscores.

True_false_null:
Is the keyword true, false, and null all lowercase lower or all uppercase upper?

Method_names:
How is the method name named? Camel = CamelCase, Lower_under = lowercase letters separated by underscores.

Method_brace_line:
Does the opening curly brace of a method be the same line as the method name or the next line in it?

Control_brace_line:
Is the opening curly brace of the control structure the same line as the declaration or the next line in it?

Control_space_after:
Is there a space after controlling the structure keyword?

Always_use_control_braces:
Does the control structure have to be enclosed within curly braces?

Else_elseif_line:
else or ElseIf with the preceding closing curly brace on the same line or in its next line?

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:
Is there a space between the function name and the opening parenthesis of the variable list in the function call statement?

Closing_php_tag_required:
Pure PHP code files, do I need to?> the end tag?

Line_endings:
Which type of line terminator is selected?

Static_or_visibility_first:
When declaring a static method, is static before or after the write access modifier?

Control_space_parens:
In the control structure, are there spaces in the left parenthesis and before the closing parenthesis? Yes = if ($expr), no = if ($expr).

blank_line_after_php:
Does PHP need a blank line after starting the tag?

Class_method_control_brace:
Start the curly braces in the position statistics for classes, methods, and control structures.

A.3. Statistical results of questionnaires
  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. 1/2:14
  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/next:4
  78. Next/next/same:11
  79. Next/same/same:1
  80. Same/same/same:6
Copy Code

Turn from GitHub (Pizzaliu)

PHP, PSR
  • Related Article

    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.