PHP _ PHP Tutorial

Source: Internet
Author: User
PHP. Documentation repository address: github. comhfcorriezfig-standardsPSR specification Chinese edition PSR-0 automatic loading PSR-1 basic code specification PSR-2 code style PSR-3 log interface why specifications excerpt Documentation documentation repository address: https://github.com/hfcorriez/fig-standards

Chinese version of the SRS specification

  • PSR-0 auto load
  • PSR-1 basic code specification
  • PSR-2 code style
  • PSR-3 log interface
Why?

Excerpt translated an official sentence. this organization aims to find a collaborative programming method by discussing the commonalities of our code projects.

I have come up with a saying in the article "Why should Google execute strict code specifications:

The code is as follows:


At Google, I can view any code and access all Google code libraries. I have the right to view them. In fact, this type of permission is available to very few people. However, I was surprised by the fact that so many coding specifications-indentation, naming, file structure, and comment style-all of which made me easily read any piece of code unexpectedly, and easily understand them. This shocked me-I thought these specifications were trivial. They cannot do this much-but they do. When you find that you can read a piece of code only by looking at the basic syntax structure of the program, this time saving can not help but be shocking!



I don't have to talk about the specifications.

Conclusion
Norms are not obligations. you can also choose your own method, but using them will make your cooperation easier. Nowadays, writing a variety of more modern applications is no longer like the past, an application generally has a lot of modules. if you do not execute the specifications, it will only make the entire project more complex to understand and communicate.

If the specifications are used, the benefits to the project and itself are self-evident.

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

Code style specification

This guide aims to reduce the cognitive differences between different developers when browsing code. To this end, we will list a group of common rules for formatting PHP code.
The commonalities of member projects constitute the style rules in this article. When different developers work together in different projects, a common standard will be used in these different projects. Therefore, the benefit of this guide is not to share the rules themselves.
In RFC 2119, the feature keyword "MUST" (MUST), "NOT" (must not), "necessary" (REQUIRED), "will" (SHALL ), "No" (shall not), "SHOULD" (shocould), "should not" (shocould NOT), "recommendation" (RECOMMENDED), "can" (MAY) and "OPTIONAL" (OPTIONAL) will be used to describe in this document.

1. Outline

The code must comply with PSR-1.

The code must be indented with four spaces instead of tabs.
The length of a line of code should not be hard to limit; the soft limit must be 120 characters; it should also be 80 characters or less.
There must be an empty line under the namespace declaration and an empty line under the use declaration code block.
The left curly braces of the class must be placed in the next row, and the right curly braces must be placed in the next row of the class body.
The left curly braces of the method must be placed in the next line, and the right curly braces must be placed under the method body.
All attributes and methods must be visible (Translator's note: Public, Protect, Private) declarations; abstract and final declarations must be prior to visibility; static declarations must be after visibility.
The keyword of the control structure must be followed by a space; methods and functions cannot.
The left curly braces of the control structure must be placed in the same row, and the right curly braces must be placed in the next row of the control body.
The left brackets of the control structure cannot be followed by spaces, and the right brackets cannot be followed by spaces.

1.1. example
This example contains the following rules:

The code is 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 ($ arg1 );
} Else {
BazClass: bar ($ arg2, $ arg3 );
}
}

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

2. Summary
2.1 Basic code specifications
The code must comply with all the rules of the 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.

Close tags for files with pure PHP code?> Must be omitted

2.3. rows
The length of a row cannot be limited.

The soft limit of line length must be 120 characters. for soft limit, the automatic style checker must warn but cannot report an error.

The actual length of a row should not exceed 80 characters. a long row should be split into multiple subsequent rows with no more than 80 characters.

No space is allowed after non-empty rows.

Empty lines can be used to improve readability and differentiate related code blocks.

A row must not contain more than one statement.

2.4. indent
The code must be indented with four spaces, and tabs cannot be used as indentations.

Note: using only spaces and not mixing with tabs helps avoid code differences, patches, history, and annotations. Space can also be used to adjust the indentions to improve the line alignment.

2.5. keyword and True/False/Null
PHP keywords must be in lower case.

PHP constants true, false, and null must be in lower case.

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

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

A use keyword must be used only for one declaration.

There must be an empty line behind the use declaration code block.

Example:

The code is as follows:


Namespace Vendor \ Package;

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

//... Additional PHP code...

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

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

The left curly braces of the class must be placed in the following line; the right curly braces must be placed behind the class body in a row.

The code is 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
}

A list of implements can be split into multiple subsequent rows with one indentation. In this case, the first item of the list must be placed in the next row, and each row must have only one interface.

The code is 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. attributes
Visibility must be declared for all attributes.

Var keywords cannot be used to declare attributes.

A statement cannot declare multiple attributes.

Attribute names should not use a single underline as a prefix to indicate protection or private visibility.

An attribute declaration should look like this.

The code is as follows:


Namespace Vendor \ Package;

Class ClassName
{
Public $ foo = null;
}

4.3. method
Visibility must be declared for all methods.

The method name should not only use a single underline to indicate protection or private visibility.

The method name cannot follow a space after the declaration. The left curly braces must be placed in the following line, and the right curly braces must be placed under the method body in a row. There must be no space at the end of the left bracket and no space at the front of the right bracket.

A method definition should look like the following. Note the following brackets:

The code is as follows:


Namespace Vendor \ Package;

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 a space after the comma.

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

The code is as follows:


Namespace Vendor \ Package;

Class ClassName
{
Public function foo ($ arg1, & $ arg2, $ arg3 = [])
{
// Method body
}
}

The parameter list can be divided into multiple subsequent rows with one indentation. In this case, the first item of the list must be placed in the next row, and each row must have only one parameter.

When the parameter list is divided into multiple rows, the right and left curly braces must be put together with a space to form a row.

The code is as follows:


Namespace Vendor \ Package;

Class ClassName
{
Public function aVeryLongMethodName (
ClassTypeHint $ arg1,
& $ Arg2,
Array $ arg3 = []
){
// Method body
}
}

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

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

The code is as follows:


Namespace Vendor \ Package;

Abstract class ClassName
{
Protected static $ foo;

Abstract protected function zim ();

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

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

Bar ();
$ Foo-> bar ($ arg1 );
Foo: bar ($ arg2, $ arg3 );
The parameter list can be split into multiple subsequent rows with one indent. In this case, the first item in the list must be placed in the next row, and each row must have only one parameter.

The code is as follows:


$ Foo-> bar (
$ LongArgument,
$ LongerArgument,
$ MuchLongerArgument
);

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

There must be a space after the control structure keyword
No space is allowed after the left parenthesis
No space before the right brackets
There must be a space between the right and left curly brackets.
The code subject must be indented once.
The right curly braces must be the next row of the subject
The subject of each structure must be enclosed in curly brackets. This structure looks more standardized, and the possibility of introducing errors can be reduced when new rows are added.

5.1. if, elseif, else

An if structure should look like the following. Note the brackets, spaces, and brackets. else and elseif are in the same line as the right curly braces of the previous subject.

The code is as follows:


If ($ expr1 ){
// If body
} Elseif ($ expr2 ){
// Elseif body
} Else {
// Else body;
}

Keyword elseif should replace else if to keep all control keywords like a word.

5.2. switch, case

A switch structure should look like the following. Note the brackets, spaces, and curly brackets. The case statement must be indented from the switch, and the break keyword (or other stop keyword) must be at the same level as the case subject indent. If a non-empty case Subject fails down, there must be a comment similar to // no break.

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 should look like the following. Note the brackets, spaces, and brackets.

The code is as follows:


While ($ expr ){
// Structure body
}


Similarly, a do while statement should look like the following. Note the brackets, spaces, and brackets.

The code is as follows:


Do {
// Structure body;
} While ($ expr );

5.4.
A for statement should look like the following. Note the brackets, spaces, and brackets.

The code is as follows:


For ($ I = 0; $ I <10; $ I ++ ){
// For body
}

5.5. foreach

A foreach statement should look like the following. Note the brackets, spaces, and brackets.

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. Note the brackets, spaces, and brackets.

The code is as follows:


Try {
// Try body
} Catch (FirstExceptionType $ e ){
// Catch body
} Catch (OtherExceptionType $ e ){
// Catch body
}

6. closure

When a closure is declared, there must be a space after the function keyword and a space before use.

The left curly braces must be in the same row, and the right curly braces must be in the next row of the subject.

There must be no space after the left brackets of the parameter list and variable list, and no space before the right brackets.

In the parameter list and variable list, there must be no space before the comma and after the comma.

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

A closure declaration should look like the following. Note the brackets, spaces, and brackets.

The code is as follows:


$ ClosureWithArgs = function ($ arg1, $ arg2 ){
// Body
};
$ ClosureWithArgsAndVars = function ($ arg1, $ arg2) use ($ var1, $ var2 ){
// Body
};

The parameter and variable list can be divided into multiple subsequent rows with one indent. In this case, the first item of the list must be placed in the next row, and only one parameter or variable must be placed in one row.

When the final list (whether it is a parameter or a variable) is divided into multiple rows, the right and left curly braces must be enclosed with a space and placed together to form a row.

The following is an example of splitting a parameter and a variable list into multiple rows.

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,
$ MuchLongerVar3
){
// 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 preceding format rules also apply.

The code is as follows:


$ Foo-> bar (
$ Arg1,
Function ($ arg2) use ($ var1 ){
// Body
},
$ Arg3
);

7. Conclusion
Many style elements and practices are intentionally ignored in this guide. These include but are not limited:

Declaration of global variables and global constants

Method declaration

Operators and assignments

Line alignment

Comments and document blocks

Class name prefix and suffix

Best practices

We recommend that you modify and extend this guide to meet these or other style elements and practices.

Appendix A Survey
To write this style guide, we used to investigate a project to determine a common practice. This survey is here for others to check.

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, no, no ,?, Yes, no, yes
Indent_type, 4, 4, 4, 4, tab, 4, tab, tab, 2, 4, 4, 4, 4, 4, tab, tab, 4, tab
Line_length_limit_soft, 75, 75, 75, no, 85,120,120, 80, 80, 80, no, 80 ,?,?, 120, 80, 150, no
Line_length_limit_hard, 85, 85, 85, 85, no, 100 ,?, No, 100,100 ,?, 120,120, no
Example, studly, example, example, lower, studly ,?, Studly, studly, studly
Class_brace_line, next, same, next, same, next, same, next, next
Constant_names, upper, upper, upper, upper
True_false_null, lower, upper, lower, lower
Method_names, camel, lower_under, camel, camel, camel, camel
Method_brace_line, next, same, next, same, next, next
Control_brace_line, same, next, same, next, same, same, same, next
Control_space_after, yes, no, yes, yes, yes, yes, yes
Always_use_control_braces, yes, no, yes, yes, yes, yes
Else_elseif_line, same, next, same, same, next, next, 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
Closing_php_tag_required, no, yes, yes, no, yes, no, no
Line_endings, LF ,?, LF ,?, LF ,?,, LF ,?, LF, LF, LF
Static_or_visibility_first, static ,?, Static, either, visibility, either, static, either ,?, Visibility ,?,?, Either, either, visibility, visibility, static ,?
Control_space_parens, no, yes, no, yes ,?, No, no
Blank_line_after_php, no, yes, yes, no, yes, yes, no, yes ,?, Yes, yes, no
Class_method_control_brace, next/same, next/same, same/same, next/next, same/same, next/next, next/same, next/same, next/next, next/same, next/same, next/same, same/same, next/same, next/next
A.2. Survey Description
Indent_type: indent type. Tab = "use tabs", 2 or 4 = "number of spaces"

Line_length_limit_soft: specifies the "soft" limit on the length of a row. it must contain characters. ? = No, or no, indicates no limit.

Line_length_limit_hard: specifies the "hard" limit of the row length. it must contain characters. ? = No or number. no indicates no limit.

Class_names: name of a class name: lower = only lowercase, lower_under = lowercase, and studly = camel.

Class_brace_line: Is the left curly braces of the class placed in the same (same) line or the next (next) line?

Constant_names: How do I name a class constant? Upper = upper case and underline separator.

True_false_null: all or all uppercase letters?

Method_names: How do I name a method? Camel = camel, lower_under = lower case with underline separator.

Method_brace_line: Is the left curly braces of the method the same (same) line or the next (next) line?

Control_brace_line: Is the left curly braces of the control structure the same (same) line or the next (next) line?

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

Always_use_control_braces: is the control structure always enclosed by curly brackets?

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

Case_break_indent_from_switch: How many times does case and break indent from the swith statement respectively?

Function_space_after: Is there a space between the function name and the left bracket of the function call?

Closing_php_tag_required: if it is a pure PHP file, close the tag?> Required?

Line_endings: which row Terminator is used?

Static_or_visibility_first: who is ahead of static and visibility when defining methods?

Control_space_parens: in the control structure expression, is there a space between the left and the right brackets? Yes = if ($ expr), no = if ($ expr ).

Blank_line_after_php: is an empty line required after the start tag of PHP?

Class_method_control_brace: the position of left curly braces 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
December 14, 1/2
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: 4
Next/same: 11
Next/same: 1
Same/same: 6

Why are PSR-0 log interfaces? why are PSR-1 log interfaces? why are PSR-2 basic code specifications loaded automatically...

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.