PHP's PSR Specification Chinese version _php tutorial

Source: Internet
Author: User
Tags case statement try catch
Document Warehouse Address: Https://github.com/hfcorriez/fig-standards

PSR Standard Chinese version

    • PSR-0 Automatic loading
    • PSR-1 Basic Code specification
    • PSR-2 Code Style
    • PSR-3 Log Interface
Why standardize

Excerpt translated the official sentence The organization aims to find a collaborative programming approach by discussing the common denominator of our code projects.

Here's an article on why Google enforces strict code standards: the

Copy CodeThe code is as follows:
At Google, I can view any code that goes into all of Google's code libraries and I have the right to view them. In fact, this is a privilege that few people can have. But what surprises me is that so many coding specifications-indentation, naming, file structure, annotation style-all of this makes me surprisingly easy to read any piece of code and easily understand them. It shocked me-because I thought these specs were trivial things. They can't have such a big effect-but they play such a big role. When you find that you can read a piece of code only by looking at the basic grammatical structure of the program, the time savings cannot be shaken!


I don't have to say anything about the norm crossing you guys.

Written in the last
The specification is not an obligation, of course you can choose your own way, but the use of norms will make your cooperation easier. Today, a variety of more modern applications are not written like before, an application generally has a lot of modules, if not to implement the specification, will only make the whole project understanding and communication more complex.

If the specification is used, the benefits to the project and itself are of course self-evident.

Reference to all accepted specifications: https://github.com/hfcorriez/fig-standards/tree/zh_CN/%E6%8E%A5%E5%8F%97

Code Style Specification

The intent of this guide is to reduce the differences in cognition when different developers browse the code. This lists a set of common rules for how to format PHP code.
The generality of each member project makes up the style rules of this article. When different developers collaborate on different projects, a common standard will be used in these different projects. Therefore, the benefits of this guide lie not in the rules themselves, but in the sharing of these rules.
Attribute keywords in RFC 2119 "must" (must), "no" (must not), "necessary" (REQUIRED), "will" (shall), "No" (shall not), "should" (should), "no" (should not) , "recommended" (RECOMMENDED), "can" (May) and "optional" (OPTIONAL) will be used in this document to describe.

1. Outline

The code must comply with PSR-1.

The code must use a 4-space indent instead of a tab.
The length of a line of code should not be rigidly limited, the soft limit must be 120 characters, and should be 80 characters or less.
There must be a blank line below the namespace declaration, and there must be a blank line underneath the use declaration code 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 the 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 note: Public, Protect, Private) declaration; abstract and final declarations must precede visibility; static declarations must be after visibility.
The key word of the control structure must be followed by a space; methods and functions are not available.
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 is no space behind the left parenthesis of the control structure, and no spaces before the right parenthesis.

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

Copy the Code code as follows:
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 ($arg 1);
} else {
Bazclass::bar ($arg 2, $arg 3);
}
}

Final public static function bar ()
{
Method body
}
}

2. Summary
2.1 Basic Code specification
The code must comply with all PSR-1 rules.

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

All PHP files must end with a blank line.

Pure PHP code file close tag?> must be omitted

2.3. Line
The line length cannot have a hard limit.

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

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

There is no space behind a non-empty line.

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

There should be no more than one statement for a row.

2.4. Indent
The code must use a 4-space indent and cannot use tabs as indentation.

Note: Using only spaces, not mixed with tabs, will help avoid some of the problems in code differences, patches, histories, and annotations. Using spaces also makes it easy to adjust the subtle indentation in order to improve the alignment of the rows.

2.5. Keywords and true/false/null
PHP keywords must use lowercase.

PHP constants True, FALSE, and null must use lowercase.

3. Namespace and use declarations
If present, namespace must have a blank line after the declaration.

If present, all use declarations must be placed under the namespace declaration.

One use keyword must be used for only one declaration.

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

Example:

Copy the Code code as follows:
namespace Vendor\package;

Use Fooclass;
Use Barclass as Bar;
Use Othervendor\otherpackage\bazclass;

... additional PHP code ...

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

4.1. Extensions 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 a class must be placed in a row below, and the right curly brace must be placed in a row behind the body of the class.

Copy the Code code as follows:
namespace Vendor\package;
Use Fooclass;
Use Barclass as Bar;
Use Othervendor\otherpackage\bazclass;

Class ClassName extends ParentClass implements \arrayaccess, \countable
{
Constants, properties, methods
}

Implements a list can be split into successive rows that have one indent at a time. If you do this, the first item of the list must be placed on the next line, and each row must have only one interface.

Copy the Code code as follows:
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
All properties must declare visibility.

The VAR keyword cannot be used to declare attributes.

A statement cannot declare multiple properties.

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

A property declaration should look like the following.

Copy the Code code as follows:
namespace Vendor\package;

Class ClassName
{
public $foo = null;
}

4.3. Methods
All methods must declare the visibility.

Method names should not only use a single underscore to indicate the visibility of protection or private.

The method name cannot follow a space after the declaration. The left curly brace must be placed in a row below, and the right curly brace must be placed in a row below the method body. There are no spaces behind the left parenthesis, and no spaces in front of the right parenthesis.

A method definition should look like this. Note parentheses, commas, spaces, and braces:

Copy the Code code as follows:
namespace Vendor\package;

Class ClassName
{
Public Function Foobarbaz ($arg 1, & $arg 2, $arg 3 = [])
{
Method body
}
}

4.4. Method parameters
In the argument list, there is no space before the comma, and a space must be followed by a comma.

A parameter with a default value in the method must be placed on the last side of the parameter list.

Copy the Code code as follows:
namespace Vendor\package;

Class ClassName
{
Public Function foo ($arg 1, & $arg 2, $arg 3 = [])
{
Method body
}
}

The argument list can be divided into multiple successive lines with one indent. If you do this, the first item of the list must be placed on the next line, and each row must have only one parameter.

When the argument list is divided into multiple lines, the closing parenthesis and the left curly brace must be enclosed in a single line with a space.

Copy the Code code as follows:
namespace Vendor\package;

Class ClassName
{
Public Function Averylongmethodname (
Classtypehint $arg 1,
& $arg 2,
Array $arg 3 = []
) {
Method body
}
}

4.5. Abstract,final and Static
If present, the abstract and final declarations must precede the visibility declaration.

If present, the static declaration must follow the visibility declaration.

Copy the Code code as follows:
namespace Vendor\package;

Abstract class ClassName
{
protected static $foo;

Abstract protected function Zim ();

Final public static function bar ()
{
Method body
}
}

4.6. Calling methods and functions
To invoke a method or function, there is no space between the method or the letter name and the opening parenthesis, no spaces after the opening parenthesis, and no spaces before the right parenthesis. In the list of functions, there is no space before the comma, and a space must be followed by a comma.

Bar ();
$foo->bar ($arg 1);
Foo::bar ($arg 2, $arg 3);
The argument list can be split into multiple successive lines with one indent. If you do this, the first item in the list must be placed on the next line, and each row must have only one parameter.
Copy the Code code as follows:
$foo->bar (
$longArgument,
$longerArgument,
$muchLongerArgument
);

5. Control structure
The style rules for the control structure are summarized as follows:

Control structure keyword must have a space after
No spaces after opening parenthesis
No spaces before closing parenthesis
There must be a space between the closing parenthesis and the left curly brace
The code body must have one indent
The right curly brace must be the next line of the body
The body of each structure must be enclosed in curly braces. This structure looks more standardized and can reduce the possibility of introducing errors when Ghanio.

5.1. If,elseif,else

An If structure should look like this. Note the position of parentheses, spaces, curly braces, and else and ElseIf on the same line as the right curly brace of the previous body.

Copy the Code code as follows:
if ($expr 1) {
If body
} elseif ($expr 2) {
ElseIf body
} else {
else body;
}

Keyword ElseIf should replace the else if use to keep all control keywords like a word.

5.2. Switch,case

A switch structure should look like this. Note brackets, spaces, and braces. The case statement must be indented from the switch, and the break keyword (or other abort keyword) must be indented at the same sibling as the case body. If a non-empty case body falls down, it must have a comment like//no break.
copy code code is as follows:
!--? PHP Switch ($expr) {
Case 0:
Echo ' first case, with a break ';
break;
Case 1:
Echo ' Second case, which fall s through ';
/No Break
Case 2:
Case 3:
Case 4:
Echo ' third case, return instead of break ';
return;
Defau LT:
Echo ' Default case ';
break;
}

5.3. While,do while
a while statement should look like this. Note the position of brackets, spaces, and braces.
copy code code is as follows:
!--? PHP while ($expr) {
//structure body
}

Similarly, a do-while statement should look like the following. Note the position of brackets, spaces, and braces.
copy code code is as follows:
!--? php do {
//structure body;
} while ($expr);

5.4. For
A For statement should look like this. Note the position of brackets, spaces, and braces.
Copy the Code code as follows:
for ($i = 0; $i < $i + +) {
For body
}

5.5. foreach

A foreach statement should look like this. Note the position of brackets, spaces, and braces.
Copy the Code code as follows:
foreach ($iterable as $key = = $value) {
foreach Body
}

5.6. Try, catch
A try catch statement should look like this. Note the position of brackets, spaces, and braces.
Copy the Code code as follows:
try {
Try Body
} catch (Firstexceptiontype $e) {
Catch body
} catch (Otherexceptiontype $e) {
Catch body
}

6. Closures

Closures must have a space after the function keyword is declared, and a space before use.

The left curly brace must be on the same line, and the right curly brace must be on the next line of the body.

There are no spaces after the left parenthesis of the argument list and the variable list, and no spaces before the closing parenthesis.

In the argument list and in the list of variables, there must be no spaces before commas, and spaces after commas.

The parameters of the closure with default values must be placed behind the parameter list.

A closure declaration should look like this. Note the position of brackets, spaces, and braces.

Copy the Code code as follows:
$closureWithArgs = function ($arg 1, $arg 2) {
Body
};
$closureWithArgsAndVars = function ($arg 1, $arg 2) use ($var 1, $var 2) {
Body
};

A list of parameters and variables can be divided into successive lines with one indent. If you do this, the first item of the list must be placed on the next line, and a row must have only one argument or variable.

When the final list (either argument or variable) is divided into multiple lines, the closing parenthesis and the left curly brace must be enclosed in a single line with a space.

The following is an example of a parameter and a list of variables that are split into multiple rows.
Copy the Code code as follows:
$longArgs _novars = function (
$longArgument,
$longerArgument,
$muchLongerArgument
) {
Body
};

$noArgs _longvars = function () use (
$longVar 1,
$longerVar 2,
$muchLongerVar 3
) {
Body
};

$longArgs _longvars = function (
$longArgument,
$longerArgument,
$muchLongerArgument
) Use (
$longVar 1,
$longerVar 2,
$muchLongerVar 3
) {
Body
};

$longArgs _shortvars = function (
$longArgument,
$longerArgument,
$muchLongerArgument
) use ($var 1) {
Body
};

$shortArgs _longvars = function ($arg) use (
$longVar 1,
$longerVar 2,
$muchLongerVar 3
) {
Body
};

Note that if the closure is called as a parameter in a function or method, the same applies to the above formatting rules.
Copy the Code code as follows:
$foo->bar (
$arg 1,
function ($arg 2) use ($var 1) {
Body
},
$arg 3
);

7. Conclusion
There are many styles of elements and practices in the guide that are intentionally overlooked. These include, but are not limited to:

Declaration of global variables and global constants

Method declaration

Operators and Assignments

Align rows

Comments and Document blocks

Class names give you prefixes and suffixes

Best practices

Future recommendations may modify and extend the guide to meet these or other stylistic elements and practices.

Appendix A survey
To write this style guide, we used a survey project to identify common practices. The survey is here for others to view.

A.1. Survey data
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. Survey Notes
Indent_type: Indentation type. tab = "Use Tab", 2 or 4 = "Number of spaces"

Line_length_limit_soft: The "soft" limit of the length of the president, with characters.? = does not mean or number no means no limit.

Line_length_limit_hard: The "hard" limit of the length of the president, with characters.? = does not mean or number, no means no limit.

Class_names: How the class name is named lower = just lowercase, Lower_under = lowercase and underlined, studly = Camel type.

Class_brace_line: Is the left curly brace of a class placed on the same (same) line or next (next)?

Constant_names: How do Class constants be named? Upper = uppercase and underlined separators.

True_false_null: Is the whole school written or capitalized?

Method_names: How is the method name named? Camel = camel, Lower_under = lowercase with underscore delimiter.

Method_brace_line: Is the left curly brace of the method in the same (same) row or the next (next) line?

Control_brace_line: Does the left curly brace of the control structure be in the same (same) row or in the next (next) line?

Control_space_after: Is there any space after controlling the structure keyword?

Always_use_control_braces: Control structures always use curly braces?

Else_elseif_line: When else and ElseIf are used, are they placed on the same (same) line or next (next)?

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

Function_space_after: Is there a space for the function name and opening parenthesis of the function call?

Closing_php_tag_required: If it is a pure PHP file, close the label?> is it necessary?

Line_endings: What line terminator to use?

Static_or_visibility_first: Static and visibility when defining a method who is in front?

Control_space_parens: In a control structure expression, do you want a space after the opening parenthesis and the right parenthesis? Yes = if ($expr), no =if ($expr).

Do I need a blank line after the start tag of the blank_line_after_php:php?

Class_method_control_brace: The position of the left curly brace in the class, method, and control structure.

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_brace_line:
Next:4
Same:18
Control_space_after:
No:2
Yes:20
Always_use_control_braces:
No:3
Yes:19
Else_elseif_line:
Next:6
Same:16
Case_break_indent_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.html www.bkjia.com true http://www.bkjia.com/PHPjc/313547.html techarticle Document Warehouse Address: Https://github.com/hfcorriez/fig-standards PSR specification Chinese version PSR-0 automatic loading PSR-1 Basic code Specification PSR-2 code style PSR-3 Log Interface Why specification excerpt ...

  • Related Article

    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.