Learning record of PSR-[0-4] code specification in php

Learning record of PSR-[0-4] code specification in php

1. What is PSR?

PSR is a set of code writing specifications used to constrain code style. In the past, when there was no standard, everyone wrote code according to their own habits, but everyone's style was different, and your code was very uncomfortable in the eyes of others. And it will lead to many problems:
Whether the function name is named hump,
Whether curly braces {} wrap,
Should I write notes or not
Whether the variable name is uppercase or lowercase,
Is it better to have one class in a php file or allow multiple classes
Therefore, the PSR-[0-4] specification came into being. Everyone abides by it, so there is no style difference.
PSR was invented by PHP-FIG, which is the abbreviation of Framework Interoperability Group. PSR is the abbreviation of Proposing a Standards Recommendation. So far, there are 5 sets of PSR specifications, namely:

PSR-0 (Autoloading Standard) Automatic loading standard
PSR-1 (Basic Coding Standard) Basic coding standard
PSR-2 (Coding Style Guide) Coding style Wizard
PSR-3 (Logger Interface) Log interface
PSR-4 (Improved Autoloading) The enhanced version loaded automatically can be replaced PSR-0 Yes.

2. Use and definition of specifications

1. PSR-0 specification

PSR-0 is the first set of specifications, which is mainly used for automatic loading of specifications, but it is now outdated and replaced by PSR-4 specification.
PSR-0 mandatory requirements:

1. A fully qualified namespace and class Must conform to such a structure:“\< Vendor Name>(< Namespace>)*< Class Name>"
2. each namespace There must be a top layer namespace("Vendor Name"(provider name)
3. each namespace You can have multiple children namespace
4. When loaded from the file system, each namespace Separator for(\)To convert to DIRECTORY_SEPARATOR(Operating system path separator)
5. In the class name, each underscore(_)Symbols to convert to DIRECTORY_SEPARATOR(Operating system path separator). stay namespace Middle, underline(_)Symbols have no (special) meaning.
6. Qualified when loaded from the file system namespace and class It must be .php Ending
7. verdor name,namespaces,class The name can be a combination of upper and lower case letters (case sensitive)

#####Article 1: a fully qualified namespace and class must conform to the following structure: "< vendor name > (< namespace >) * < class name >"

If my file path is lib / driver / config PHP, then the declaration and use of My namespace are:

Affirms that: namespace \Lib\Driver;
use: use \Lib\Driver\Config;

#####Article 2 and 3: each namespace must have a top-level namespace ("Vendor Name" provider name), and each namespace can have multiple child namespaces

namespace \Lib\Driver\Config->/path/to/vender/Lib/Driver/Config.php

Lib is the top-level namespace and Driver is the sub namespace/

#####Article 4: when loading from the file system, the separator () of each namespace shall be converted to directory_ Separator (operating system path separator)

new \Lib\Driver\Config->The converted directory is/Lib/Driver/Config.php,Replace backslash with directory separator

#####Article 5: in the class name, each underscore () Symbol to convert to directory_ Separator (operating system path separator). In namespace, underline () Symbols have no (special) meaning

\Lib\Driver\Class_Name->Convert to directory/Lib/Driver/Class/Name.php
\Lib\Package_Name\Class_Name->Convert to directory/Lib/Package_Name/Class/Name.php

In the directory_ Is an underscore. The underscore in classname is actually converted into a path separator.
#####However, this provision has been cancelled in PSR-4 and no conversion is required.

#####Article 6: when loading from the file system, the qualified namespace and class must be in php ending

The loaded file must be php end, since php is used, of course php is over. No more php3,php5 like before

#####Article 7: verdor name, namespaces and class name can be composed of upper and lower case letters (case sensitive)

Because Linux is case sensitive and windows is case insensitive, if you don't pay attention to the case, you can develop normally under win, but you may not be able to execute normally on the server.

2. PSR-1 specification

requirement:

1. PHP Source files must use only <?php and <?= These two labels.
2. In source file php The encoding format of code must be without byte order mark(BOM)of UTF-8. 
3. A source file is recommended only for declarations (classes)(class),function(function),constant(constant)Or it is only used to do some operations that cause side effects (e.g. output information, modify).ini Configuration, etc.),But it is not recommended to do both at the same time.
4. Namespace(namespace)And class(class) Must comply PSR-0 Standard.
5. Class name(class name) Camel style must be used(StudlyCaps)Writing method (Note: hump type(cameCase)A variant of, which will be used directly later StudlyCaps express). 
6. class(class)Constants in must consist only of uppercase letters and underscores(_)form.
7. Method name(method name) Hump type must be used(cameCase)Writing.
Article 1: PHP source files must only use <? PHP and <= These two labels

Because php has four tag forms, which one to use is specified here and standardized.

Article 2: the encoding format of php code in the source file must be UTF-8 without byte order mark (BOM)

By default, the windows notebook will add BOM header to the file header, which will lead to strange output on the server.
The domestic Chinese code is GBK, and UTF-8 is an international common code. If it is not unified, it will also lead to confusion.

Article 3: a source file is recommended to be used only for declarations (classes, functions, constants, etc.) or only for operations that cause side effects (such as outputting information, modifying. ini configuration, etc.), but it is not recommended to do both at the same time.

Don't define functions and modify system configuration in a file. A file only does one thing.

// Side effects: the ini configuration has been modified
ini_set('error_reporting', E_ALL);
// Side effects: file loaded
include "file.php";
// Side effects: output
echo "<html>\n";
// Declaration function
function foo()
{
    // Function body
}

Write separately

// Declaration function
function foo()
{
    // Function body
}
// Side effects: modified ini configuration
ini_set('error_reporting', E_ALL);
// Side effects: file loaded
include "file.php";

It's neat.

Article 4: namespaces and classes must comply with PSR-0 standards

See PSR-0 standard

Article 5: class name must be written in studycaps (Note: a variant of camel case, which will be directly expressed in studycaps later).

The class name must be named by hump, large hump and small hump can be used.

<?php
class BigHouse{
}
Article 6: constants in a class must consist only of uppercase letters and underscores () form.
<?php
class Test{
	const USER_INFO = 'xx';
	const NAME = 'xx';
}
Article 7: method name must be written in camel case.
<?php
class Test{
	public function getUserInfo(){}
}

Summary: Although the specification does not specify whether to use large hump or small hump, my development habit is class name large hump and method name small hump

3. PSR-2 specification

PSR-2 is used to constrain the code style. The code must follow all the rules listed in PSR-1.

1. Source file
  1. The end of the file must be a blank line.
  2. UNIX LF (line feed) must be used as the line terminator.
  3. Close tag of pure PHP code source file? > Must be omitted.
2. OK
  1. The President shall not have rigid restrictions.
  2. The soft limit of line length must be 120 characters; The automatic Style Checker must warn, but cannot make errors at soft limits.
  3. The line should not exceed 80 characters; Lines longer than this length should be split into multiple lines with no more than 80 characters per line.
  4. Non blank lines must not have trailing spaces at the end.
  5. Empty lines can be added to improve readability and indicate related code blocks.
  6. No more than one statement per line.
3. Indent

Code must be indented with 4 spaces and must not be indented with tabs. Modern editors can be set.

Note: using only spaces, rather than mixing spaces with tabs, can help avoid problems with differences, patches, history, and comments. The use of spaces also makes it easy to insert fine-grained sub indents for line alignment.

4. Keyword and True/False/Null
  1. PHP keywords must be lowercase.
  2. PHP constants true, false, and null must be lowercase.
5. Use and declaration of namespace
  1. A namespace declaration must be followed by an empty line.
  2. All import (use) declarations must be placed below the namespace declaration.
  3. There must be only one import (use) keyword in a statement.
  4. There must be an empty line after the import (use) declaration code block.
<?php
namespace Vendor\Package;//You must leave a blank line below

use FooClass;//Put use under the namespace
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;//There should also be a blank line below use

// ... additional PHP code ...

6. Classes, attributes and methods
  1. Extensions and implementation must be written on the same line as class name, and curly braces should be written on a new line.
<?php
namespace Vendor\Package;

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

//Write on one line
class ClassName extends ParentClass implements \ArrayAccess, \Countable
{//Curly bracket wrap
    // constants, properties, methods
}

Multiple implementations can be written in multiple lines, but the first must be on the next line. Each line can only write one interface, and each line should be indented.

<?php
namespace Vendor\Package;

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

class ClassName extends ParentClass implements
    \ArrayAccess,//The first interface should be written on the next line. Pay attention to indentation
    \Countable,
    \Serializable
{
    // constants, properties, methods
}
  1. Attribute must declare visibility, public or private or protected, and cannot be omitted. You can't use VaR, which is the way in the old version of php, for public. Property names should not be prefixed with a single underscore to indicate protected or private visibility. You cannot declare more than one attribute per statement.
<?php
namespace Vendor\Package;

class ClassName
{
    public $foo = null;
}
  1. Method, its visibility must be declared. Whether it is public or protected or private, it cannot be omitted. In addition, curly braces {must be written on a new line. If there are multiple parameters, the first parameter shall be followed by a space. If the parameter has a default value, it shall also be separated by left and right spaces.
<?php
namespace Vendor\Package;

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

The parameter list can be divided into multiple lines, which need to be indented as interface multiple lines. When there are multiple lines of parameters, curly braces need not be written on a new line, but a space should be left after the right bracket. As follows:

<?php
namespace Vendor\Package;

class ClassName
{
    public function aVeryLongMethodName(
        ClassTypeHint $arg1,
        &$arg2,
        array $arg3 = []
    ) {
        // method body
    }
}
  1. When abstract and final are used for class declaration, they must be placed before the visibility declaration (public or protected or private). When static is used for class declaration, it must be placed after the visibility declaration.
<?php
namespace Vendor\Package;

abstract class ClassName
{
    protected static $foo; //Put the static modifier after the visibility declaration

    abstract protected function zim();//abstract to the front

    final public static function bar()//final put it to the front
    {
        // method body
    }
}
  1. When calling a function, there shall be no space between the function name and the left bracket, no space after the left bracket and no space before the right bracket. In the parameter list, there must be no space before each comma and one space after each comma. The parameter list can be divided into multiple lines, with each subsequent line indented once. In doing so, the first item in the list must be on the next row, and each row must have only one parameter.
<?php
bar();
$foo->bar($arg1);
Foo::bar($arg2, $arg3);
$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);
7. Control structure
  1. The control structure is process control such as if and switch. The general rules are as follows:
  2. There must be a space after the control structure keyword
  3. There must be no spaces after the left parenthesis
  4. There must be no space before the closing bracket
  5. There must be a space between the right brace and the left brace
  6. The structure must be indented once
  7. The closing brace must be on the next line after the body
1. if, else if, else:
<?php
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

Else if should be written continuously. Don't write else if. Look like a word.

2. switch,case:
<?php
switch ($expr) {//There should be spaces before and after parentheses
    case 0:
        echo 'First case, with a break';
        break;//break should be aligned with the previous line
    case 1:
        echo 'Second case, which falls through';
        //If there is no break statement, write a comment no break
        // no break
    case 2:
    case 3:
    case 4:
        echo 'Third case, return instead of break';
        return;
    default:
        echo 'Default case';
        break;
}
3. while,do while
<?php
while ($expr) {
    // structure body
}

do {
    // structure body;
} while ($expr);
4. for,foreach
<?php
for ($i = 0; $i < 10; $i++) {
    // for body
}

foreach ($iterable as $key => $value) {
    // foreach body
}
5. try,catch
<?php
try {
    // try body
} catch (FirstExceptionType $e) {
    // catch body
} catch (OtherExceptionType $e) {
    // catch body
}
8. Closure
  1. Closures must be declared with spaces after the function keyword and use before and after the keyword
  2. The left brace must be on the same line and the right brace must be on the next line after the body.
  3. There shall be no space after the left bracket of the parameter list or variable list, and there shall be no space before the right bracket of the parameter list or variable list.
  4. In the parameter list and variable list, there cannot be a space before each comma, and there must be a space after each comma.
  5. Closure parameters with default values must be placed at the end of the parameter list.
  6. The parameter list and variable list can be divided into multiple lines, with each subsequent line indented once. In doing so, the first item in the list must be on the next row, and each row must have only one parameter or variable
  7. When the input parameter list (whether parameters or variables of use) is divided into multiple lines, the right and left parentheses must be placed on their own line with a space between them.
  8. Note that formatting rules also apply when closures are used directly as arguments in a function or method.
<?php
$closureWithArgs = function ($arg1, $arg2) {
    // body
};

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


//Parameter list formatting
$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
};

//Closures are passed in as parameters
$foo->bar(
    $arg1,
    function ($arg2) use ($var1) {
        // body
    },
    $arg3
);

4. PSR-3 specification

PSR-3 specification is the general interface of log library. The general framework can help us do a good job and understand it. Official website document

5. PSR-4 specification

PSR-4 is also an automatic loading specification to replace PSR-0.

  1. Repealed PSR-0_ That's how the directory separator is written_ Underscores have no special meaning in fully qualified class names.
  2. The class file name should start with php end.
  3. As like as two peas as like as two peas, the class name must be exactly the same as the corresponding file name.

Summary:

Psr-0 and psr-4 are automatic loading specifications, psr-1 and psr-2 are code style specifications, and psr-3 is the log library interface.
In our daily work, we try to use psr-1 and psr-2 specifications to standardize our code style.

Keywords: PHP server

Added by DrAxeman on Tue, 25 Jan 2022 23:08:53 +0200