Home > Backend Development > PHP Tutorial > PHP PSR specification Chinese version_PHP tutorial

PHP PSR specification Chinese version_PHP tutorial

WBOY
Release: 2016-07-21 16:12:53
Original
1146 people have browsed it

Document warehouse address: https://github.com/hfcorriez/fig-standards

PSR specification Chinese version

  • PSR-0 automatically loaded
  • PSR-1 Basic Code Specification
  • PSR-2 code style
  • PSR-3 Logging Interface
Why the specification

Excerpt translates an official sentence. This organization aims to find out the commonalities of our code projects by discussing A collaborative programming approach.

I am reminded of this passage in an article "Why Google Enforces Strict Code Standards":

Copy code The code is as follows:

In Google, I can view any code, enter all Google code libraries, and I have permission to view them. In fact, very few people have this kind of authority. However, what surprised me was that so many coding standards—indentation, naming, file structure, comment style—all made it surprisingly easy for me to read any piece of code and understand them easily. This shocked me—because I thought these norms were trivial. They couldn't possibly have done that much—yet they did. When you find that you can understand a piece of code just by looking at the basic syntax structure of the program, this kind of time saving cannot but be shocking!


Dear readers, I don’t need to say more about the regulations.

Write it at the end
Specifications are not obligatory. Of course, you can also choose your own way, but using specifications will make your cooperation easier. Nowadays, the writing of various more modern applications is no longer like before. An application generally consists of many modules. If the specifications are not implemented, it will only make the understanding and communication of the entire project more complicated.

If you use specifications, the benefits to the project and yourself are of course self-evident.

All accepted specification references: https://github.com/hfcorriez/fig-standards/tree/zh_CN/%E6%8E%A5%E5%8F%97

Code Style Specification

The purpose of this guide is to reduce the cognitive differences between different developers when browsing code. This enumerates a set of common rules for how to format PHP code.
The commonalities of each member project form the style rules of this article. When different developers collaborate on different projects, a common standard will be used across these different projects. Therefore, the benefit of this guide lies not in the rules themselves, but in sharing them.
The characteristic keywords in RFC 2119 are "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", The words "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" will be used in this document.

1. Outline

Code must comply with PSR-1.

Code must use 4 spaces indentation, not tabs.
There should be no hard limit on the length of a line of code; the soft limit must be 120 characters; it should also be 80 characters or less.
There must be a blank line below the namespace declaration, and there must also be a blank line below the use declaration block.
The left curly brace of the class must be placed on the next line, and the right curly brace must be placed on the next line of the class body.
The left curly brace of a method must be placed on the next line, and the right curly brace must be placed below the method body.
All properties and methods must have visibility (Translator's Note: Public, Protect, Private) declarations; abstract and final declarations must be before visibility; static declarations must be after visibility.
Keywords of control structures must have a space after them; methods and functions are not allowed.
The left curly brace of the control structure must be placed on the same line, and the right curly brace must be placed on the next line of the control body.
There must be no spaces after the left bracket of the control structure and no spaces before the right bracket.

1.1. Example
This example contains a simple display of some of the above rules:

Copy code The code is as follows:

namespace VendorPackage;
use FooInterface;
use BarClass as Bar;
use OtherVendorOtherPackageBazClass;

class Foo extends Bar implements FooInterface
{
public function sampleFunction($a, $b = null)
{
if ($a === $b) {
bar ();
} elseif ($a > $b) {
                                                                                               );
}
}

final public static function bar() {

// method body
}
}

2. Summary
2.1 Basic code specifications
Code must comply with all rules of PSR-1.

2.2 Files
All PHP files must use Unix LF (line feed) as the line terminator.

All PHP files must end with a blank line.

File closing tag for pure PHP code?>Must be omitted

2.3. Line
There cannot be a hard limit on line length.

The soft limit on line length must be 120 characters; for the soft limit, the automatic style checker must warn but not error.

The actual line length should not exceed 80 characters; longer lines should be split into multiple subsequent lines of no more than 80 characters.

There must be no spaces after non-blank lines.

Blank lines can be used to improve readability and distinguish related blocks of code.

There should be no more than one statement per line.

2.4. Indentation
Code must use 4 spaces for indentation, and tab characters cannot be used as indentation.

Note: Using only spaces, not mixed with tabs, will help avoid some problems in code differences, patches, history and comments. Using whitespace also makes it very easy to adjust subtle indentations to improve alignment between lines.

2.5. Keywords and True/False/Null
PHP keywords must be lowercase.

PHP constants true, false and null must be lowercase.

3. Namespace and Use declarations
If present, there must be a blank line after the namespace declaration.

If present, all use statements must be placed below the namespace statement.

A use keyword must be used in only one declaration.

There must be a blank line after the use declaration block.

Example:

Copy code The code is as follows:

namespace VendorPackage;

use FooClass;
use BarClass as Bar;
use OtherVendorOtherPackageBazClass;

// ... additional PHP code ...

4. Classes, properties and methods
The term "class" refers to all classes, interfaces and traits.

4.1. Extension and inheritance
The extends and implements keywords of a class must be on the same line as the class name.

The left curly brace of the class must be placed on its own line below; the right curly brace must be placed on its own line after the class body.

Copy code The code is as follows:

namespace VendorPackage;
use FooClass;
use BarClass as Bar;
use OtherVendorOtherPackageBazClass;

class ClassName extends ParentClass implements ArrayAccess, Countable
{
// constants, properties, methods
}

implements that a list can be split into multiple subsequent lines with one indentation. If you do this, the first item in the list must be placed on the next line, and there must be only one interface per line.

Copy code The code is as follows:

namespace VendorPackage;

use FooClass;
use BarClass as Bar;
use OtherVendorOtherPackageBazClass;

class ClassName extends ParentClass implements
ArrayAccess,
Countable,
Serializable
{
// constants, properties, methods
}

4.2. Attributes
All attributes must declare visibility.

The var keyword cannot be used to declare attributes.

One statement cannot declare multiple attributes.

Property names should not be prefixed with a single underscore to indicate protected or private visibility.

A property declaration should look like this.

Copy code The code is as follows:

namespace VendorPackage;

class ClassName
{
public $foo = null;
}

4.3. Methods
All methods must declare visibility.

Method names should not use only a single underscore to indicate protected or private visibility.

The method name cannot be followed by a space after the declaration. The opening curly brace must be placed on its own line below, and the closing curly brace must be placed on its own line below the method body. There must be no spaces after the left bracket and no spaces before the right bracket.

A method definition should look like the following. Note the brackets, commas, spaces and curly braces:

Copy code The code is as follows:

namespace VendorPackage;

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

4.4. Method parameters
In the parameter list, there must be no space before the comma, and there must be one space after the comma.

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

Copy code The code is as follows:

namespace VendorPackage;

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

The parameter list can be divided into multiple subsequent lines with one indentation. If you do this, the first item in the list must be placed on the next line, and only one parameter must be placed on each line.

When the parameter list is divided into multiple lines, the right bracket and the left curly bracket must be placed together with a space to form a line of their own.

Copy code The code is as follows:

namespace VendorPackage;

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

4.5. abstract, final and static
If present, abstract and final declarations must be placed before the visibility declaration.

If present, a static declaration must be followed by a visibility declaration.

Copy code The code is as follows:

namespace VendorPackage;

abstract class ClassName
{
protected static $foo;

abstract protected function zim();

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

4.6. Calling methods and functions
To call a method or function, there must be no space between the method or function name and the left bracket, no space after the left bracket, and no space before the right bracket. In the function list, there must be no space before the comma, and there must be one space after the comma.

bar();
$foo->bar($arg1);
Foo::bar($arg2, $arg3);
The parameter list can be Split into subsequent lines with an indent. If you do this, the first item in the list must be placed on the next line, and each line must have exactly one argument.

Copy code The code is as follows:

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

5. Control structure
The style rules for control structures are summarized 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 left curly bracket
Code The body must be indented once
The closing curly brace must be one line below the body
The body of each structure must be enclosed in curly braces. This structure looks more standardized and reduces the possibility of introducing errors when adding new lines.

5.1. if, elseif, else

An if structure should look like the following. Pay attention to the placement of parentheses, spaces, and curly braces; and else and elseif are on the same line as the closing curly brace of the previous body.

Copy code The code is as follows:

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

The keyword elseif should be used instead of else if to keep all control keywords as one word.

5.2. switch, case

A switch structure should look like the following. Pay attention to the parentheses, spaces and curly braces. The case statement must be indented from the switch, and the break keyword (or other break keyword) must be indented at the same level as the case body. If a non-empty case body falls down, there must be a comment like // no break.

Copy code The code is as follows:

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, do while
a while statement It should look like this. Pay attention to the placement of parentheses, spaces, and curly braces.
Copy code The code is as follows:

while ($expr) {
// structure body
}

Similarly, a do while statement should look like the following. Pay attention to the placement of parentheses, spaces, and curly braces.
Copy code The code is as follows:

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

5.4. for
A for statement should look like the following. Pay attention to the placement of parentheses, spaces, and curly braces.

Copy code The code is as follows:

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

5.5. foreach

A foreach statement should look like the following. Pay attention to the placement of parentheses, spaces, and curly braces.

Copy code The code is as follows:

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

5.6. try, catch
A try catch statement should look like the following. Pay attention to the placement of parentheses, spaces, and curly braces.
Copy code The code is as follows:

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

6. Closure

There must be a space after the function keyword when the closure is declared, and a space is also required before use.

The opening curly brace must be on the same line, and the closing curly brace must be on the next line of the body.

There must be no spaces after the left parenthesis of parameter lists and variable lists, and there must be no spaces before the right parentheses.

In parameter lists and variable lists, there must be no spaces before the comma and there must be spaces after the comma.

Parameters of closures with default values ​​must be placed after the parameter list.

A closure declaration should look like the following. Pay attention to the placement of parentheses, spaces, and curly braces.

Copy code The code is as follows:

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

Parameter and variable lists can be split into multiple subsequent lines with one indentation. If you do this, the first item in the list must be placed on the next line, and only one parameter or variable must be placed on a line.

When the final list (whether parameters or variables) is divided into multiple lines, the right bracket and the left curly bracket must be placed on their own line with a space.

Below is an example of a parameter and variable list split into multiple lines.

Copy code The code is as follows:

$longArgs_noVars = function (
$longArgument,
$longerArgument,
$muchLongerArgument
) {
// body
} ;

$noArgs_longVars = function () use (
$longVar1,
$longerVar2,
$muchLongerVar3
) {
// body
};

$longArgs_longVars = function (
$longArgument,
$longerArgument,
$muchLongerArgument
) use (
$longVar1,
$longerVar2,
$muchLongerVar 3
) {
// body
};

$longArgs_shortVars = function (
$longArgument,
$longerArgument,
$muchLongerArgument
) use ($var1) {
// body
};

$shortArgs_longVars = function ($arg) use (
$longVar1,
$longerVar2,
$muchLongerVar3
) {
// body
};


Note that if the closure is called as a parameter in a function or method, the above formatting rules also apply.
Copy code The code is as follows:

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

7. 结论
在该指南中有很多风格的元素和做法有意被忽略掉。这些包括但不局限于:

全局变量和全局常量的声明

方法声明

操作符和赋值

行间对齐

注释和文档块

类名给你前缀和后缀

最佳实践

以后的建议可以修改和扩展该指南以满足这些或其他风格的元素和实践。

附录A 调查
为了写这个风格指南,我们采用了调查个项目以确定共同的做法。这个调查在这里供他人查看。

A.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
voting,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,no,no,no,?,yes,no,yes
indent_type,4,4,4,4,4,tab,4,tab,tab,2,4,tab,4,4,4,4,4,4,tab,tab,4,tab
line_length_limit_soft,75,75,75,75,no,85,120,120,80,80,80,no,100,80,80,?,?,120,80,120,no,150
line_length_limit_hard,85,85,85,85,no,no,no,no,100,?,no,no,no,100,100,?,120,120,no,no,no,no
class_names,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,lower_under,studly,lower,studly,studly,studly,studly,?,studly,studly,studly
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
constant_names,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper
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
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
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
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
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
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
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
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
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
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
line_endings,LF,LF,LF,LF,LF,LF,LF,LF,?,LF,?,LF,LF,LF,LF,?,,LF,?,LF,LF,LF
static_or_visibility_first,static,?,static,either,either,either,visibility,visibility,visibility,either,static,either,?,visibility,?,?,either,either,visibility,visibility,static,?
control_space_parens,no,no,no,no,no,no,yes,no,no,no,no,no,no,yes,?,no,no,no,no,no,no,no
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
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
A.2. 调查说明
indent_type: 缩进类型。 tab = "使用制表符",2 or 4 = "空格数量"

line_length_limit_soft: 行长度的“软”限制,用字符。 ? = 不表示或者数字 no 意为不限制.

line_length_limit_hard: 行长度的"硬"限制,用字符。 ? = 不表示或者数字, no 意为不限制.

class_names: 类名如何命名 lower = 只是小写, lower_under = 小写加下划线, studly = 骆驼型.

class_brace_line: Should the opening brace of a class be placed on the same line or on the next line?

constant_names: How to name class constants? upper = uppercase plus underline delimiter.

true_false_null: Write in all letters or all capital letters?

method_names: How to name methods? camel = camel case, lower_under = lowercase plus underline delimiter.

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

control_brace_line: Is the left brace of the control structure on the same line or the next line?

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

always_use_control_braces: Always use curly braces for control structures?

else_elseif_line: When using else and elseif, should they be placed on the same line or on the next line?

case_break_indent_from_switch: How many times are case and break indented from the switch statement?

function_space_after: Are there spaces in the function name and left bracket of the function call?

closing_php_tag_required: If it is a pure PHP file, closing the tag?>Is it required?

line_endings: What line endings to use?

static_or_visibility_first: Which one comes first, static or visibility, when defining a method?

control_space_parens: In the control structure expression, is there a space after the left bracket and before the right bracket? yes = if ( $expr ), no =if ($expr).

blank_line_after_php: Is a blank line required after the PHP start tag?

class_method_control_brace: The position of the left curly brace in classes, methods and control structures.

A.3. Survey results
indent_type:
tab: 7
2: 1
4: 14
line_length_limit_soft:
?: 2
no: 3
75: 4
80: 6
85: 1
100: 1
120: 4
150: 1
line_length_limit_hard:
?: 2
no : 11
85: 4
100: 3
120: 2
class_names:
?: 1
lower: 1
lower_under: 1
studly: 19
class_brace_line:
next: 16
same: 6
constant_names:
upper: 22
true_false_null:
lower: 19
upper: 3
method_names: Camel: 21
LOWER_UNDER: 1
Method_brace_line:
Next: 15
Same: 7
Control_line_line:
NEXT: 4
Same: 18
Control_space _Affter:
no: 2
yes: 20
always_use_control_braces:
no: 3
yes: 19
else_elseif_line:
next: 6
same: 16
case_break_in dent_from_switch :
0/1: 4
1/1: 4
1/2: 14
function_space_after:
no: 22
closing_php_tag_required:
no: 19
yes: 3
line_endings:
?: 5
LF: 17
static_or_visibility_first:
?: 5
either: 7
static: 4
visibility: 6
control_space_parens:
?: 1
no: 19
yes: 2
blank_line_after_php:
?: 1
no: 13
yes: 8
class_method_control_ brace:
next/next/next: 4
next/next/same: 11
next/same/same: 1
same/same/same: 6

http://www.bkjia.com/PHPjc/313547.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/313547.htmlTechArticleDocument warehouse address: https://github.com/hfcorriez/fig-standards PSR specification Chinese version PSR-0 Automatically load PSR-1 basic code specification PSR-2 code style PSR-3 log interface Why is the specification excerpt translated...
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template