[PHP series] PHP recommended standard PSR-1, PSR-2, psr-1psr-2

Source: Internet
Author: User
Tags traits

[PHP series] PHP recommended standard PSR-1, PSR-2, psr-1psr-2

At least the code. When I first went to college, the teacher taught us to write the code strictly and properly. The code is like a person, and the work is complete. The canonicalized code is controlled from the very beginning when you use the command line to edit the C language code, and you are forced to follow the relevant standards. Therefore, writing code is not standard, I would like to give myself a thumbs up for the good habits I made at that time.

Now written to PHP, for PHP, whether there are related code standards, of course, you may be reading other blogs or PHP related documents often mention these terms, PSR-1, PSR-2 and so on, this is the Recommendation specification developed by the PHP-FIG, today, we will be able to understand the PHP Recommendation standard, the PSR (PHP Standards Recommendation ).

Note: The PHP-FIG has abandoned the first recommendation specification, PSR-0, the first recommendation specification was replaced by the new release of the PSR-4.

PSR-1: Basic code style: http://www.php-fig.org/psr/psr-1/

PSR-2: strict code style: http://www.php-fig.org/psr/psr-2/

PSR-3: logger interface: http://www.php-fig.org/psr/psr-3/

PSR-4: auto load: http://www.php-fig.org/psr/psr-4/

The above URL must be connected to a vpn to open, no vpn? Buy one, and it will cost dozens of dollars a year.

Today we bring the main code specification, PSR-1, PSR-2 on the Code style specification.

PSR-1 basic code style Overview
  • Files MUST use only<?phpAnd<?=Tags.

  • Files MUST use only UTF-8 without BOM for PHP code.

  • Files shocouldEitherDeclare symbols (classes, functions, constants, etc .)OrCause side-effects (e.g. generate output, change. ini settings, etc.) but shocould NOT do both.

  • Namespaces and classes MUST follow an "autoloading" stated by: [PSR-0, PSR-4].

  • Class names MUST be declared inStudlyCaps.

  • Class constants MUST be declared in all upper case with underscore separators.

  • Method names MUST be declared incamelCase.

PHP labels

PHP code MUST use the long<?php ?>Tags or the short-echo<?= ?>Tags; it must not use the other tag variations.

Encoding

PHP code MUST use only UTF-8 without BOM.

Function. Classes, methods, and constants cannot be ambiguous.

A file shoshould declare new symbols (classes, functions, constants, etc.) and cause no other side effects, or it shoshould execute logic with side effects, but shoshould NOT do both.

The following is an example of a file with both declarations and side effects; I. e, an example of what to avoid:

<?php// side effect: change ini settingsini_set('error_reporting', E_ALL);// side effect: loads a fileinclude "file.php";// side effect: generates outputecho "

The following example is of a file that contains declarations without side effects; I. e., an example of what to emulate:

<?php// declarationfunction foo(){    // function body}// conditional declaration is *not* a side effectif (! function_exists('bar')) {    function bar()    {        // function body    }}
Namespace and Class Name

Each class is in a file by itself, and is in a namespace of at least one level: a top-level vendor name. the term "class" refers to all classes, interfaces, and traits (traits, partial implementation of classes ).

 

Code written for PHP 5.3 and after MUST use formal namespaces.

For example:

<?php// PHP 5.3 and later:namespace Vendor\Model;class Foo{}
Constant

Class constants MUST be declared in all upper case with underscore separators. (all uppercase letters can be underlined below) For example:

<?phpnamespace Vendor\Model;class Foo{    const VERSION = '1.0';    const DATE_APPROVED = '2012-06-01';}
Variable

This guide intentionally avoids any recommendation regarding the use$StudlyCaps,$camelCase, Or$under_scoreProperty names)

Method

Method names MUST be declared incamelCase(). (The method name adopts the camper method)

Strict code style PSR-2

In the official website, this is the code specification, PSR-1 is only the basic code specification, if you only want the basic, then the following content can be ignored, I personally suggest to follow this code specification.

Overview
  • Code MUST follow a "coding style guide" stated [PSR-1].

  • Code MUST use 4 spaces for indenting, not tabs.

  • There must not be a hard limit on line length; the soft limit MUST be 120 characters; lines shoshould be 80 characters or less.

  • There MUST be one blank line afternamespaceDeclaration, and there MUST be one blank line after the blockuseDeclarations.

  • Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.

  • Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.

  • Visibility MUST be declared on all properties and methods;abstractAndfinalMUST be declared before the visibility;staticMUST be declared after the visibility.

  • Control structure keywords MUST have one space after them; method and function cils must not.

  • Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.

  • Opening parentheses for control structures must not have a space after them, and closing parentheses for control structures must not have a space before.

Example

This example encompasses some of the rules below as a quick overview:

<?phpnamespace Vendor\Package;use FooInterface;use BarClass as Bar;use OtherVendor\OtherPackage\BazClass;class Foo extends Bar implements FooInterface{    public function sampleMethod($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    }}
Basic Style

Code MUST follow all rules outlined in PSR-1.

File

All PHP files MUST use the Unix LF (linefeed) line ending.

All PHP files MUST end with a single blank line.

The closing?>Tag MUST be omitted from files containing only PHP.

Maybe you have written PHP code before. Here, the PHP file cannot be empty at the end and cannot be used?> End label.

Code line length

Lines shoshould NOT be longer than 80 characters; lines longer than that shoshould be split into multiple subsequent lines of no more than 80 characters each.

Indent

Code MUST use an indent of 4 spaces, and must not use tabs for indenting.

N. b.: Using only spaces, and not mixing spaces with tabs, helps to avoid problems with diffs, patches, history, and annotations. the use of spaces also makes it easy to insert fine-grained sub-indentation for inter-line alignment.

Keywords

PHP keywords MUST be in lower case.

The PHP constantstrue,false, AndnullMUST be in lower case.

Namespace

When present, there MUST be one blank line afternamespaceDeclaration.

When present, alluseDeclarations MUST go afternamespaceDeclaration.

There MUST be oneuseKeyword per declaration.

There MUST be one blank line afteruseBlock.

For example:

<?phpnamespace Vendor\Package;use FooClass;use BarClass as Bar;use OtherVendor\OtherPackage\BazClass;// ... additional PHP code ...
Extends and Implements

TheextendsAndimplementsKeywords MUST be declared on the same line as the class name.

<?phpnamespace Vendor\Package;use FooClass;use BarClass as Bar;use OtherVendor\OtherPackage\BazClass;class ClassName extends ParentClass implements \ArrayAccess, \Countable{    // constants, properties, methods}
Variable

Visibility (public, private, protected) MUST be declared on all properties.

ThevarKeyword must not be used to declare a property.

There must not be more than one property declared per statement.

Property names shocould NOT be prefixed with a single underscore to indicate protected or private visibility. Here is shocould NOT. I personally think it SHOULD be MUST NOT.

A property declaration looks like the following.

<?phpnamespace Vendor\Package;class ClassName{    public $foo = null;}
Method

Visibility MUST be declared on all methods.

Method names shoshould NOT be prefixed with a single underscore to indicate protected or private visibility. Here is shocould NOT. I personally think it SHOULD be MUST NOT.

The opening brace MUST go on its own line, and the closing brace MUST go on the next line following the body.

<?phpnamespace Vendor\Package;class ClassName{    public function fooBarBaz($arg1, &$arg2, $arg3 = [])    {        // method body    }}
Method Parameters

In the argument list, there must not be a space before each comma, and there MUST be one space after each comma.

Method arguments with default values MUST go at the end of the argument list.

<?phpnamespace Vendor\Package;class ClassName{    public function foo($arg1, &$arg2, $arg3 = [])    {        // method body    }}

When the argument list is split into SS multiple lines, the closing parenthesis and opening brace MUST be placed together on their own line with one space between them.

<?phpnamespace Vendor\Package;class ClassName{    public function aVeryLongMethodName(        ClassTypeHint $arg1,        &$arg2,        array $arg3 = []    ) {        // method body    }}
Abstract, final, and static

When present,abstractAndfinalDeclarations MUST precede the visibility declaration.

When present,staticDeclaration MUST come after the visibility declaration.

<?phpnamespace Vendor\Package;abstract class ClassName{    protected static $foo;    abstract protected function zim();    final public static function bar()    {        // method body    }}
Method call

When making a method or function call,

There must not be a space between the method or function name and the opening parenthesis,

There must not be a space after the opening parenthesis, and there must not be a space before the closing parenthesis.

In the argument list, there must not be a space before each comma, and there MUST be one space after each comma.

<?phpbar();$foo->bar($arg1);Foo::bar($arg2, $arg3);
Control Structure
  • There MUST be one space after the control structure keyword
  • There must not be a space after the opening parenthesis
  • There must not be a space before the closing parenthesis
  • There MUST be one space between the closing parenthesis and the opening brace
  • The structure body MUST be indented once
  • The closing brace MUST be on the next line after the body
If, elseif, else

AnifStructure looks like the following. Note the placement of parentheses, spaces, and braces; and thatelseAndelseifAre on the same line as the closing brace from the earlier body.

<?phpif ($expr1) {    // if body} elseif ($expr2) {    // elseif body} else {    // else body;}
Switch, case

AswitchStructure looks like the following. There MUST be a comment such// no breakWhen fall-through is intentional in a non-emptycaseBody.

<?phpswitch ($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;}
While, do while
<?phpwhile ($expr) {    // structure body}
<?phpdo {    // structure body;} while ($expr);
For, foreach
<?phpfor ($i = 0; $i < 10; $i++) {    // for body}
<?phpforeach ($iterable as $key => $value) {    // foreach body}
Try, catch
<?phptry {    // try body} catch (FirstExceptionType $e) {    // catch body} catch (OtherExceptionType $e) {    // catch body}
Anonymous Functions

Closures MUST be declared with a space afterfunctionKeyword, and a space before and afteruseKeyword.

The opening brace MUST go on the same line, and the closing brace MUST go on the next line following the body.

There must not be a space after the opening parenthesis of the argument list or variable list, and there must not be a space before the closing parenthesis of the argument list or variable list.

In the argument list and variable list, there must not be a space before each comma, and there MUST be one space after each comma.

Closure arguments with default values MUST go at the end of the argument list.

A closure declaration looks like the following. Note the placement of parentheses, commas, spaces, and braces:

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

The line feed of those parameters will not be described here. It may make the code messy. I do not recommend that you write comments on the parameters of the method. Annotations are very important, I would rather discard some standards and write more comments. The standards should be less written, which is difficult to read. If there are fewer comments, I cannot read them.

Well, today I'm talking about the PSR-1 and PSR-2 for the code specification, and next I will bring you PSR-3 log specification and PSR-4 auto loader related content. A good start is the basic element of success. I hope everyone can abide by the code specifications. After all, the code is like a person, and the work is complete. Pai_^

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.