Home  >  Article  >  Backend Development  >  PHP PSR-2 coding style specification

PHP PSR-2 coding style specification

WBOY
WBOYOriginal
2016-07-23 08:54:441157browse
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 coding styles when browsing the code of different authors by formulating a series of rules for standardizing PHP code.

When multiple programmers collaborate in multiple projects, a common coding specification is needed.
The style specification in this article is derived from the common characteristics of the coding styles of multiple different projects.
Therefore, the value of this specification lies in We all follow this coding style, not in itself.

Keywords "must" ("MUST"), "must not/must not" ("MUST NOT"), "need" ("REQUIRED"),
"will" ("SHALL"), "won't" ("SHALL NOT"), "should" ("SHOULD"), "should not" ("SHOULD NOT"),
"recommended" ("RECOMMENDED"), "can" ("MAY") and "optional" ("OPTIONAL") is described in detail in [RFC 2119][].

Overview


Code must follow the coding conventions in [PSR-1][].

Codemustuse 4 spaces instead of the tab key for indentation.

The number of characters per line should be softly kept within 80. Theoretically must not exceed 120, but must not have a hard limit.

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

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

Class properties and methods must add access modifiers (private, protected and public), abstract and final must be declared before the access modifier, while static

must

be declared after the access modifier. There must be a space after the keyword of the control structure, but there must not be when calling a method or function.

The opening curly brace ({)

of the control structure must be written on the same line as the declaration, while the closing curly brace (}) must be written on its own line after the body.

There must be no

spaces after the opening left bracket and before the closing right bracket of the control structure. 1.1. Example The following example program simply demonstrates most of the above specifications:

namespace VendorPackage;

use FooInterface;

use BarClass as Bar;
use OtherVendorOtherPackageBazClass; {
public function sampleFunction($a, $b = null)
    {
  1. if ($a === $b) {
  2. bar();
  3. } elseif ($a > $b) {
  4. $foo-> ;bar($arg1);
  5. } else {
  6. BazClass::bar($arg2, $arg3);
  7. }
  8. }
  9. final public static function bar()
  10. {
  11. // method body
  12. }
  13. }
  14. Copy code
  15. General rules


    2.1 Basic Coding Guidelines

    Code must comply with all specifications in [PSR-1][].

    2.2 Documentation

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

    All PHP files must end with a blank line.

    Pure PHP code filesmustomit the final ?> closing tag.

    2.3. OK

    The length of the line must not have a hard limit.

    The soft length constraintmustbe limited to 120 characters. If it exceeds this length, the editor with code specification checkmustissue a warning, but must notissue an error prompt.

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

    There must not be any extra spaces after the non-blank line.

    Blank lines can make it easier to read code and help to chunk the code.

    Each line must not contain more than one statement.

    2.4. Indentation

    Codemustuse 4 spaces for indentation, must notuse the tab key.

    Note: The advantage of using spaces instead of tab keys for indentation is that
    avoids confusion when comparing code differences, patching, re-reading code, and comments.
    Also, use spaces for indentation to make alignment easier.

    2.5. Keywords and True/False/Null

    PHP all [keywords][]mustall lowercase.

    The constants true, false and null also must be all lowercase.

    namespace and use declaration


    A blank line must be inserted after the namespace declaration.

    All uses must be declared after namespace.

    Each use statement must have only one use keyword.

    There must be a blank line after the use statement block is declared.

    For example:

    1. namespace VendorPackage;
    2. use FooClass;
    3. use BarClass as Bar;
    4. use OtherVendorOtherPackageBazClass;
    5. // ... additional PHP code ...
    Copy code

    Classes, properties and methods


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

    4.1. Extension and inheritance

    The keywords extends and implementsmust be written on the same line as the class name.

    The opening brace

    of a class must occupy its own line, and the closing brace must occupy its own line after the class body. ? & Lt;? Phpnamespace VendorPackage;

    use Fooclass;
    use Barclass as Bar; Parentclass Implements ArrayAccess, Countable
      {
    1. // constants, Properties, Methods
    2. }
    3. Copy code
    4. implements’ inheritance list can also
    5. be split into multiple lines. In this case, each inherited interface name
    6. must be separated into separate lines, including the first one.
    namespace VendorPackage;

    use FooClass;use BarClass as Bar;use OtherVendorOtherPackageBazClass;

    class ClassName extends ParentClass implements
    ArrayAccess,
    Countable,
      Serializable
    1. {
    2. // constants, properties, methods
    3. }
    4. Copy code
    5. 4.2. Properties
    6. Each property
    7. must
    8. have an access modifier added.
    9. Must not
    use the keyword var to declare a property.
    Each statement must not
    define more than one attribute.

    Don’t

    use an underscore as a prefix to distinguish whether a property is protected or private.

    The following is an example of property declaration:

    namespace VendorPackage;

    class ClassName{

    public $foo = null;

    }

    Copy code
    1. 4.3. Method
    2. All methods
    3. must
    4. add access modifiers.
    5. Don’t
    use underscore as a prefix to distinguish whether a method is protected or private.
    There must be no spaces after the method name. The opening curly brace
    must

    be on its own line, and the closing curly brace must be on its own line after the method body. There must be no spaces after the left bracket and before the right bracket of the parameter.

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

    namespace VendorPackage;class ClassName{ public function fooBarBaz($arg1, &$arg2, $arg3 = []) { // method body

    }

    }

    Copy code
    4.4. Parameters of method

    In the parameter list, must have a space after each comma, and must not have a space before the comma.

    Parameters with default values ​​must be placed at the end of the parameter list.

    1. namespace VendorPackage;
    2. class ClassName
    3. {
    4. public function foo($arg1, &$arg2, $arg3 = [])
    5. {
    6. // method body
    7. }
    8. }
    Copy the code

    The parameter list can be split into multiple lines, so that each parameter, including the first parameter, must be on its own line.

    After splitting the parameter list into multiple lines, the closing bracket and the opening brace of the method must be written on the same line, separated by a space in the middle.

    1. namespace VendorPackage;
    2. class ClassName
    3. {
    4. public function aVeryLongMethodName(
    5. ClassTypeHint $arg1,
    6. &$arg2,
    7. array $arg3 = []
    8. ) {
    9. // method body
    10. }
    11. }
    Copy code
    4.5. abstract, final, and static

    When you need to add abstract or final declaration, must be written before the access modifier, and static must be written after it.

    1. namespace VendorPackage;
    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 code
    4.6. Method and function calls

    When calling methods and functions, there must be no spaces between the method name or function name and the left parentheses of the parameters, and there must not be spaces before the right parentheses of the parameters. Each parameter must not have a space before it, but must have a space after it.

    bar();
  16. $foo->bar($arg1);
  17. Foo::bar($arg2, $arg3);
Copy code
parameters
OK

Split into multiple lines. At this time, each parameter including the first parameter must be in a separate line.

$foo->bar(
    $longArgument,
  1. $longerArgument,
  2. $muchLongerArgument
  3. );
  4. Copy code
Control structure

The basic specifications of the control structure are as follows:


There must be

a space after the control structure keyword.

There must be no space after the left bracket (.

There must be no space before the right bracket ).

There must be

a space between the right bracket ) and the opening curly bracket { .

The main body of the structure must

be indented once. The closing curly brace }

must be placed on a separate line after the body of the structure.

The body of each structure must

be enclosed in pairs of curly braces,

This makes the structure more structured and reduces the possibility of errors when adding new lines. 5.1. if , elseif and else The standard if structure is as shown in the following code. Pay attention to the position of brackets, spaces, and curly braces.

Note that else and elseif are both on the same line as the previous closing curly brace.


if ($expr1) {
// if body

} elseif ($expr2) {
// elseif body
} else {
    // else body;
  1. }
  2. Copy The code
  3. should
use the keyword elseif instead of all else if s so that all control keywords appear to be a single word.
5.2. switch and case The standard switch structure is as shown in the following code. Pay attention to the position of brackets, spaces and curly braces. The case statement
must be indented relative to the switch, while the break statement and other statements within the case must be indented relative to the case.

If there is a non-empty case through statement, there must be a comment like // no break in the body.


switch ($expr) {
case 0:
echo 'First case, with a break';

break;
case 1:
echo 'Second case, which falls through';
    // no break
  1. case 2:
  2. case 3:
  3. case 4:
  4. echo 'Third case, return instead of break';
  5. return;
  6. default:
  7. echo 'Default case';
  8. break;
  9. }
  10. Copy Code
  11. 5.3. while and do while

    A standardized while statement should look like the following, pay attention to the position of brackets, spaces, and curly braces.

    1. while ($expr) {
    2. // structure body
    3. }
    Copy code

    The standard do while statement is as follows. Likewise, pay attention to the brackets, spaces and flowers. The position of the brackets.

    1. do {
    2. // structure body;
    3. } while ($expr);
    Copy code
    5.4. for

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

    1. for ($i = 0; $i < 10; $i++) {
    2. // for body
    3. }
    Copy code
    5.5. foreach

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

    1. foreach ($iterable as $key => $value) {
    2. // foreach body
    3. }Copy code5.6. try, catch

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

      1. try {
      2. // try body
      3. } catch (FirstExceptionType $e) {
      4. // catch body
      5. } catch (OtherExceptionType $e) {
      6. // catch body
      7. }
      Copy code

      Closure


      When a closure is declared, there must be a space after the keyword function and before and after the keyword use. The opening brace

      must

      be written on the same line as the declaration, and the closing brace must follow the line immediately following the end of the body. There must be no

      spaces after the left bracket and before the right bracket in the parameter list and variable list.

      In the parameter and variable lists, must not

      have spaces before the comma, and

      must have spaces after the comma. Parameters with default values ​​ in the closure must

      be placed at the end of the list.

      The standard closure declaration statement is as follows, pay attention to the position of parentheses, commas, spaces and curly braces.

      $closureWithArgs = function ($arg1, $arg2) {
        // body
      1. };
      2. $closureWithArgsAndVars = function ($arg1, $arg2) use ($var1, $var2) {
      3. // body
      4. };
      5. Copy code
      Parameter lists and variable lists can
    be split into multiple lines, so that each parameter or variable, including the first one,

    must be on its own line, while The closing brace of the list and the opening curly brace of the closure must be placed on the same line. The following examples include multiple situations where parameter and variable lists are divided into multiple lines.

    $longArgs_noVars = function (
      $longArgument,
    1. $longerArgument,
    2. $muchLongerArgument
    3. ) {
    4. // body
    5. };
    6. $noArgs_longVars = function () use (
    7. $longVar 1,
    8. $longerVar2,
    9. $muchLongerVar3
    10. ) {
    11. // body
    12. };
    13. $longArgs_longVars = function (
    14. $longArgument,
    15. $longerArgument,
    16. $muchLongerArgument
    17. ) use (
    18. $longVar1,
    19. $longerVar2 ,
    20. $muchLongerVar3
    21. ) {
    22. // body
    23. };
    24. $longArgs_shortVars = function (
    25. $longArgument,
    26. $longerArgument,
    27. $muchLongerArgument
    28. ) use ($var1) {
    29. // body
    30. };
    31. $shortArgs_longVars = function ( $arg) use (
    32. $longVar1,
    33. $longerVar2,
    34. $muchLongerVar3
    35. ) {
    36. // body
    37. };
    38. Copy code
    Note that when closures are used directly as parameters for function or method calls, The above rules still apply.

    $foo->bar(
      $arg1,
    1. function ($arg2) use ($var1) {
    2. // body
    3. },
    4. $arg3
    5. );
    6. Copy Code

Summary


There are inevitably some oversights in the above specifications, including but not limited to:

Definition of global variables and constants

Definition of function

Operators and assignments

Inline alignment

Comments and documentation blocks

Prefix and suffix of class name

Best Practices

Subsequent revisions and expansions of this specification will make up for the above shortcomings.

Appendix A. Questionnaire

In order to write this specification, the team developed a questionnaire to collect statistics on the common specifications of each member's project.
The following is the data from this questionnaire survey, available for review 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,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 code
A.2. Questionnaire instructions

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 per line. ? = no answer or no answer, no means no limit.

line_length_limit_hard:
The "hard" limit on the number of characters per line. ? = no answer or no answer, no means no limit.

class_names:
Naming of class names. lower = only lowercase letters allowed, lower_under = lowercase letters separated by underscores, studly = StudlyCase camel case style.

class_brace_line:
Is the opening brace of the class on the same line as the class keyword or on the next line?

constant_names:
How to name the constants of the class? upper = uppercase letters separated by underscores.

true_false_null:
Are the keywords true, false and null all lowercase or all uppercase?

method_names:
How to name method names? camel = camelCase, lower_under = lowercase letters separated by underscores.

method_brace_line:
Is the opening brace of the method on the same line as the method name or on the next line?

control_brace_line:
Is the opening brace of the control structure on the same line as the declaration or on the next line?

control_space_after:
Is there a space after the control structure keyword?

always_use_control_braces:
Are control structures always enclosed in curly braces?

else_elseif_line:
else or elseif Is the

else or elseif on the same line as the preceding closing curly brace or on the next line?


case_break_indent_from_switch:

How many times do the case and break in the switch statement need to be indented relative to the switch?


function_space_after:

In the function call statement, is there a space between the function name and the left bracket of the variable list?


closing_php_tag_required:

Does a file with pure PHP code need a ?> closing tag?


line_endings:

What type of line endings to choose?


static_or_visibility_first:

When declaring a static method, should static be written before or after the access modifier?


control_space_parens:

In the control structure, are there spaces after the left bracket and before the right bracket? yes = if ( $expr ), no = if ($expr).


blank_line_after_php:

Does PHP need a blank line after the opening tag?


class_method_control_brace:

Start curly brace position statistics in classes, methods and control structures.
A.3. Questionnaire statistics results 问INDENT_TYPE:
TAB: 7
    2: 1
  1. 4: 14
  2. line_length_limit_soft:
  3. ?: 2
  4. no: 3
  5. 75: 4
  6. 85: 1
  7. 100 100 : 1
  8. 120: 4
  9. 150: 1
  10. line_length_limit_hard:
  11. ?: 2
  12. no: 11
  13. 85: 4
  14. 100: 3
  15. 120: 2
  16. class_names:
  17. ?: 1
  18. lower: 1
  19. _under: lower 1
  20. studly : 19
  21. class_brace_line:
  22. next: 16
  23. same: 6
  24. constant_names:
  25. upper: 22
  26. true_false_null:
  27. lower: 19
  28. upper: 3
  29. method_names:
  30. camel: 21
  31. lower_under: 1
  32. method_brace_line:
  33. next: 15
  34. same: 7
  35. control_brace_line:
  36. next: 4
  37. same: 18
  38. control_space_after:
  39. no: 2
  40. yes: 20
  41. always_use_control_braces:
  42. no: 3
  43. yes: 19
  44. else_elseif_line:
  45. next: 6
  46. same: 16
  47. case_break_indent_from_switch:
  48. 0/1: 4
  49. 1/1: 4
  50. 1/2: 14
  51. function_space_after:
  52. no: 22
  53. closing_php_tag_required:
  54. no: 19
  55. yes: 3
  56. line_endings:
  57. ?: 5
  58. LF: 17
  59. static_or_ visibility_first:
  60. ?: 5
  61. either: 7
  62. static: 4
  63. visibility: 6
  64. control_space_parens:
  65. ?: 1
  66. no: 19
  67. yes: 2
  68. blank_line_after_php:
  69. ?: 1
  70. no: 13
  71. yes: 8
  72. class_method_control_brace :
  73. next/next/next: 4
  74. next/next/same: 11
  75. next/same/same: 1
  76. same/same/same: 6
  77. Copy code
Reposted from Github (PizzaLiu)

PHP, PSR

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn