» » PHP PSR-2 code style specification

 

PHP PSR-2 code style specification

Author: bamboo06 on 2-02-2019, 17:26, views: 35

0
This specification is an inheritance and extension of the PSR-1 basic code specification. This specification hopes to reduce the inconvenience caused by the different styles of the code when browsing the code of different authors by formulating a series of rules for normalizing PHP code.
PHP PSR-2 code style specification

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

1. Overview
The code must follow the coding conventions in PSR-1.
The code must be indented using 4 spaces instead of the tab key.
The number of characters per line should be kept within 80. In theory, there must be no more than 120, but there must be no hard limit.
After each namespace namespace declaration statement and the use declaration statement block, a blank line must be inserted.
The beginning curly brace ({) of the class must be written as a line after the function declaration, and the closing curly braces (}) must also be written in the body of the function.
The beginning of the method curly brace ({) must be written in a line after the function declaration, the end of the curly braces (}) must also be written in the body of the function itself.
Class properties and methods must add access modifiers (private, protected, and public), abstract and final must be declared before the access modifier, and static must be declared after the access modifier.
There must be a space character after the control structure's keyword, and there must be no way to call a method or function.
The opening curly brace ({) of the control structure must be written on the same line of the declaration, and the closing curly brace (}) must be written on the subject itself.
There must be no spaces after the opening left parenthesis and before the closing right parenthesis of the control structure.
1.1. Examples

The following example program simply shows most of the above specifications:

<php
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
    }
}


2. General rules
2.1 Basic coding guidelines

The code must conform to all specifications in PSR-1.

2.2 Documentation

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

All PHP files must end with a blank line.

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

2.3. Line

The length of the line must not be rigidly constrained.

The length constraint of the softness must be limited to 120 characters. If the length is exceeded, the editor with the code specification check must issue a warning, but must not issue an error.

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

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

Blank lines can make reading code more convenient and help block the code.

There must be no more than one statement per line.

2.4. Indentation

The code must be indented with 4 spaces, and the tab must not be used.

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

2.5. Keywords and True/False/Null

All PHP keywords must be all lowercase.

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

3. namespace and use statement
A blank line must be inserted after the namespace declaration.

All use must be declared after the namespace.

Each use statement must have only one use keyword.

Use must have a blank line after the statement block is declared.

E.g:

<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

// ... additional PHP code ...


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

4.1. Extension and inheritance

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

The beginning curly braces of the class must be on a separate line, and the closing curly braces must also be on a separate line after the class body.

<?php
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 can also be divided into multiple lines, so that each inherited interface name must be separated into separate lines, including the first one.

<?php
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. Properties

Each attribute must have an access modifier added.

You must not declare a property with the keyword var .

Each statement must not define more than one attribute.

Do not use an underscore as a prefix to distinguish whether the attribute is protected or private.

The following is an example of a property declaration:

<?php
namespace Vendor\Package;

class ClassName
{
    public $foo = null;
}


4.3. Method

All methods must add an access modifier.

Do not use an underscore as a prefix to distinguish between protected or private.

There must be no spaces after the method name. The beginning curly braces must be on a separate line. The closing curly braces must also be on a separate line after the method body. There must be no spaces after the left parenthesis and before the right parenthesis.

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

<?php
namespace Vendor\Package;

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


4.4. Method parameters

In the parameter list, there must be a space after each parameter, and there must be no spaces in front.

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

<?php
namespace Vendor\Package;

class ClassName
{
    public function foo($arg1, &$arg2, $arg3 = [])
    {
        // method body
    }
}


The parameter list can be divided into multiple lines so that each parameter, including the first parameter, must be in a separate line.

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

<?php
namespace Vendor\Package;

class ClassName
{
    public function aVeryLongMethodName(
        ClassTypeHint $arg1,
        &$arg2,
        array $arg3 = []
    ) {
        // method body
    }
}


4.5. abstract , final , and static

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

<?php
namespace Vendor\Package;

abstract class ClassName
{
    protected static $foo;

    abstract protected function zim();

    final public static function bar()
    {
        // method body
    }
}


4.6. Methods and function calls

When a method or function is called, there must be no spaces between the method name or function name and the parameter left parenthesis. There must be no spaces before the right parenthesis. There must be no spaces before each parameter, but there must be a space after it.

<?php
bar();
$foo->bar($arg1);
Foo::bar($arg2, $arg3);


Parameters can be divided into multiple rows, and each parameter including the first parameter must be in a separate row.

<?php
$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);


5. Control structure
The basic specifications of the control structure are as follows:

There must be a space after the control structure keyword.
Left parenthesis (There must be no spaces afterwards.
There must be no spaces before the closing parenthesis.
There must be a space between the closing parenthesis and the opening curly braces {.
The body of the structure must be indented once.
End curly braces } Must be in a separate line after the body of the structure.
The body of each structure must be contained in pairs of curly braces.
This allows the structure to be more structured and less likely to go wrong when joining a new line.

5.1. if , elseif and else

The standard if structure is shown in the following code, paying attention to the position of parentheses, spaces, and curly braces.
Note that both else and elseif are on the same line as the previous closing curly brace.

<?php
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}


You should use the keyword elseif instead of all else if so that all control keywords are treated as a single word.

5.2. switch and case

The standard switch structure is shown in the following code, paying attention to the position of parentheses, spaces, and curly braces.
The case statement must be indented relative to the switch, and the break statement and other statements in 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.

<?php
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 while

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

<?php
while ($expr) {
    // structure body
}


The standard do while statement is shown below, as well as the position of the parentheses, spaces, and curly braces.

<?php
do {
    // structure body;
} while ($expr);


5.4. for

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

<?php
for ($i = 0; $i < 10; $i++) {
    // for body
}


5.5. foreach

The standard foreach statement looks like this, noting the position of its parentheses, spaces, and curly braces.

<?php
foreach ($iterable as $key => $value) {
    // foreach body
}


5.6. try, catch

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

<?php
try {
    // try body
} catch (FirstExceptionType $e) {
    // catch body
} catch (OtherExceptionType $e) {
    // catch body
}


6. Closure
When a closure declaration is made, there must be a space after the keyword function and before and after the keyword use.

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

There must be no spaces after the left parenthesis and before the right parenthesis of the parameter list and variable list.

In the list of parameters and variables, there must be no spaces before the comma, and there must be spaces after the comma.

Parameters with default values in the closure must be placed after the list.

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

<?php
$closureWithArgs = function ($arg1, $arg2) {
    // body
};

$closureWithArgsAndVars = function ($arg1, $arg2) use ($var1, $var2) {
    // body
};


The parameter list and the variable list can be divided into multiple lines, so that each parameter or variable including the first one must be in a separate line, and the closing parentheses of the list must be placed on the same line as the opening curly brace of the closure.

The following examples include multiple cases where the parameter and variable list are divided into multiple rows.

<?php
$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 that the above rules still apply when a closure is used directly as a parameter to a function or method call.

<?php
$foo->bar(
    $arg1,
    function ($arg2) use ($var1) {
        // body
    },
    $arg3
);


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

Definition of global variables and constants

Definition of function

Operators and assignments

Inline alignment

Comment and document description block

Prefix and suffix of class name

Best Practices

Tags: php, psr, code

Category: PHP Scripts

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
Information
Comment on the news site is possible only within (days) days from the date of publication.