PHP Coding standards PHP Coding Standard

Source: Internet
Author: User
Tags autoload coding standards php coding standards

Conversion from: PHP writing specification PHP Coding Standard

PHP writing specifications
By sink <sink.cup@gmail.com>
Last modified: 2011-7-13

References:
PHP Manual
Http://www.php.net/manual/zh/language.oop5.basic.php
PEAR Coding Standards
Http://pear.php.net/manual/en/standards.php
C ++ Coding Standard
Http://www.possibility.com/Cpp/CppCodingStandard.html
Google C ++ Style Guide
Http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
Code Conventions for the Java
Http://www.oracle.com/technetwork/java/codeconvtoc-136057.html

Note the following when formulating specifications:
1. Generally, do not use either of them.
For example, both tab and four spaces can be used, resulting in code confusion.

General principles:
1. semantic
You can see the name.

2. General prefix
Is indicates whether or not, get indicates read, set indicates write. Is followed by adjectives rather than nouns. For example, if it is a multi-language text, is_multilingual should be used instead of is_multilanguage.

3. singular and plural
Refer to the function naming rules of js: getElementById, getElementsByTagName, and getElementsByName.
For example:
Use getFriendsName instead of getFriendNames or getFriendName to retrieve the names of multiple friends.
GetUser
GetUsers

4. Redundant suffixes
Do not use data, list, or info suffixes unless otherwise specified.
For example, js naming requires that you use getElementsByTagName instead of getElementsInfoByTagName.
GetFriends or getFriendsUserId should be used instead of getFriendsList; getUser should be used instead of getUserInfo or getUserData.
However, it is sometimes difficult to avoid it. For example, two functions are used to retrieve basic user information and user details.
Get the basic user information: nickname, profile picture URI, function name getUserBasic or getUserBasicInfo? The function name ended with an adjective does not feel appropriate. To be discussed. Discussion result: getUserBasicInfo is suitable.
Get user details: nickname, profile picture URI, signature, birthday, function name getUser no problem.

5. Fuzzy class name, file name, and directory name
Every time you use common, util, functions, class, object, and basic as file names, be cautious. Because these words are too common, there will be more and more things in them and they will become garbage bins. To give these accurate names, such as the class for string processing, it can be called StringLib. php and put in the lib directory.

6. Differences between lib, plugin, and addon
Some classes and functions are calculated as lib, plugin, or addon. To be discussed. Discussion result: currently, the enhancement function is Lib. We will consider plugin and addon later.

7. Common Words
The URI is preferred, not the URL. Because it is more rigorous, the new name begins to use URI. For example, the js encodeURI, PHP $ _ SERVER ['request _ URI '].
Deadline and TTL: deadline indicates the last time, and TTL indicates the survival time. For example, if the current time is 1310449710 and TTL is 60 seconds, deadline is 1310449710 + 60 = 1310449770.

Class Name:
Start with an upper-case letter and name the camper. Generally, nouns are used, such as ConfigParser, rather than ParseConfig.
It is consistent with Java and C ++.
Example: class UserModel

Class File Name:
Same as the class name. This is related to php autoload. For autoload, the class name is always long. To be discussed. Discussion results: automatic class loading can also be achieved by following the hump.
Same as Java.
For example, the file name of class UserModel is UserModel. php.

Non-class file name:
Lowercase letters, underscores (_), and spaces are not allowed. For example, get_user.php.

Directory Name:
Lowercase letters, underscores (_), and spaces are not allowed. Such as model and www.

Function Name:
Start with a lowercase letter and name it in the hump, for example, function addBlog ().
It is consistent with Java and C ++.
A function indicates a function, that is, an action. Therefore, the verb takes precedence. For example, you can use editBlog instead of blogEdit.
Due to historical reasons, PHP built-in functions have various styles, such as do_something, something_do, and dosomething. The Newer functions use doSomething, which is consistent with the current mainstream languages.
For example, paser_str, json_encode, substr, and fetchAll.
Historical reasons may not change, but we can ensure that the new Code is rigorous and do not make ourselves the historical reasons.

Functions in the class:
There is a blank line between the two functions. If there is time, the functions are sorted by English letters to avoid confusion.
For example:
Class BlogModel
{
Public function addBlog ()
{

}

Public function updateBlog ()
{

}
}

File notes:
Note followed by <? Next line in php. Indicate the author. @ Version does not need to be written at the moment, because svn provides version management.
Format according to PHPdoc requirements: http://manual.phpdoc.org/HTMLframesConverter/default/phpDocumentor/tutorial_tags.author.pkg.html
<? Php
/**
* Various blog services: Add and update
* @ Author sink
*
*/
Class BlogModel
{

}
?>

API notes:
Be sure to write the input parameters and output format. Write clearly what is output when it is correct, and what is output when it is incorrect.
Otherwise, it cannot be used by others.

Function notes:
Make sure to write the output format. Write clearly what is output when it is correct, and what is output when it is incorrect.
If the input parameters are complex and contain arrays, you must write a comment on the input parameters.
There cannot be blank lines between document comments and functions.
If the internal steps of the function are complex, you need to write "intra-row comments ".
For example:
/**
* Update a blog
* @ Param int $ id blog_id
* @ Param array $ data array (
"Content" => "", // content
"Tags" => "", // tag
"Update_time" => "", // Update Time
)
* @ Return bool
*/
Public function updateBlog ($ id, $ data)
{
Step 1 // Step 1: asdf
Step 2 // Step 2: qwer
}

URI:
According to rfc1034 international standards, underlines (_) are not allowed in the domain name. The domain name is case insensitive.
For example, http: // dl_dir.qq.com/is the incorrect domain name.
The http://example.com is the same as the http://EXAMPLE.COM.
Therefore, the lower-case URI is preferred, except for the GET value.
For example
Http://www.google.com /? Hl = zh-CN
Http://www.google.com /? Hl = zh-cn
Whether the abbreviation of a non-parameter exclusive term in URI is in lowercase is controversial.
For example
Http://fedoraproject.org/zh_CN/
Http://zh.wikipedia.org/zh-cn/
Http://code.google.com/intl/zh-CN/
Http://www.microsoft.com/en-us/
The language code is a special term. ISO requires a minus sign, and it is recommended that uppercase letters be used for the region.
The usage of fedora is strange. It uses its own zh_CN instead of zh-CN. We do not recommend that you use underscores (_) in the URI.
Wiki uses lower-case letters, google uses upper-case letters, and Microsoft uses lower-case letters.

The minus sign "-" is preferred in the URI, not the underline, except for the GET name.
For example
Http://example.com/1-2-2
Http://example.com /? User_id = 123
If you want to manually enter the URI, It is case-insensitive and the lower case is preferred, because the user input is more convenient.
The actual situation is: users generally manually enter the domain name, rather than manually enter the URI, because the URI is very long. In this case, is URI lowercase meaningful if http://example.com/is used /? UserId = 123, the variable name can use $ userId = $ _ GET ['userid'] to be consistent with Java and C ++. In this way, the database name must also be camped. To be discussed. Discussion result: use? User_id = 123.

Variable:
Lowercase letters, separated by underscores (_), for example, $ user_id.
Different from Java and C ++. Discussion result: $ user_id is used.
Class member variables, function parameters, class instantiation into an object, all comply with the variable naming rules.
Cause: the URI and database have lower case conventions. The parameters obtained from $ _ GET and $ _ POST are stored in the database, so the values are in lower case.
PHP built-in variables $ _ GET and $ _ POST start with an underline, all uppercase. Do not start a custom variable with an underscore no matter how important it is to avoid conflicts with built-in variables in the future.
For example, do not use $ _ PUT or $ _ DELETE.

Constant:
All are uppercase and separated by underscores. Such as const MEMCACHE_TTL = 600;

PHP short labels:
Use <? Php?>, Do not use short labels <? ?>. It conflicts with xml and is not conducive to deployment.

Class braces wrap:
You can use braces to separate one line, or put braces in one line with other lines. There is no final dispute to be discussed. Discussion results: Use "peers ".
Class UserModel {

}
Support for changers:
Http://www.php.net/manual/zh/language.oop5.basic.php
Http://pear.php.net/manual/en/standards.classdef.php

Function braces wrap:
There are no final points to be discussed. Discussion results: Use "peers ".
Function getUser (){

}
Support for changers:
Http://www.php.net/manual/zh/language.oop5.basic.php
Http://pear.php.net/manual/en/standards.funcdef.php

If braces wrap:
There are no final points to be discussed. Discussion results: Use "peers ".
For example:
If (! Empty ($ name ))
{

}
Or
If (! Empty ($ name) {// OK

}
Support for changers:
Http://www.possibility.com/Cpp/CppCodingStandard.html#brace

Support peers:
Http://www.php.net/manual/zh/language.oop5.basic.php
Http://pear.php.net/manual/en/standards.control.php

Switch braces wrap:
Discussion results: Use "peers ".
Switch (...){
Case 1:
...
Break;

Default:
}
Support for changers:
Http://www.possibility.com/Cpp/CppCodingStandard.html#switch

Array parentheses wrap:
Controversial and inconclusive. Discussion results: Use "peers ".
$ User = array (
"Id" => "123 ",
"Name" => "user1 ",
"Email" => "a@example.com ",
)
Support peers:
Http://pear.php.net/manual/en/standards.arrays.php

Line feed inside the array:
Wrap the array of two or more dimensions.
For example
$ User = array (
'Id' => '123 ',
'Name' => 'user1 ',
'Email '=> 'a @ example.com ',
);
The line feed is not included in the dimension array. Result: The line feed is not included in the 1-dimension array.
For example
$ Users_id = array ('23', '12', '24'); // OK

The last comma of the array:
Each row of the array must have a comma at the end to facilitate subsequent addition. However, the front-end JSON cannot end with a comma; otherwise, Some browsers do not support it and will be discussed later. Discussion results: all works, because the backend does not need to consider the IE front-end.
For example
$ User = array (
'Id' => '123 ',
'Name' => 'user1', // All, advantages: Large Array, often add a row, convenient. If there is no comma, it is too difficult to add it.
);
$ User = array (
'Id' => '123 ',
'Name' => 'user1' // yes. Advantage: strict. Comma (,) indicates separation. The last one does not need to be separated.
);

Single quotation marks and double quotation marks:
Single quotation marks are preferred. Double quotation marks are used when escape is required. variables are not placed in double quotation marks. This is different from JSON. JSON is full of double quotation marks and will be discussed later. Discussion result: single quotation marks are preferred.
For example:
Echo 'name is: '. $ name.'. '. "\ n ";
$ User = array (
'Id' => '123 ',
);

Braces for condition judgment:
There must be braces, even if there is only one line.
Correct:
If (! Empty ($ name )){
DoSomething ();
}
Error:
If (! Empty ($ name ))
DoSomething ();

Carriage return line feed:
Use a line break LF (\ n, 0a, Unix style ). Do not use CR + LF (Windows style ).
Reference: http://zh.wikipedia.org/zh-cn/%E6%8F%9B%E8%A1%8C
Eclipse -- "workspace --" New text file line delimiter -- "Other: Unix

Encoding:
Use the UTF-8 no BOM. Do not use Windows notepad to save, because notepad is a UTF-8 bom cr + LF.
Eclipse -- workspace -- Text file encoding -- Other: UTF-8

Indent:
Use four spaces for indentation, or tab for indentation. Discussion result: 4 spaces.
Four spaces are supported: // OK
Http://www.oracle.com/technetwork/java/codeconventions-136091.html#262

Two spaces are supported:
Http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Spaces_vs._Tabs

Three, four, or eight spaces are supported:
Http://www.possibility.com/Cpp/CppCodingStandard.html#indent

Make sure that the indentation is correct. If four spaces are used, do not contain five or 11 spaces.
Eclipse -- General -- Editor -- Text Editors -- show whitespace characters
Vim ~ /. Vimrc
Set expandtab
Set softtabstop = 4
Set shiftwidth = 4
Set autoindent

HTTP protocol cache:
The Last Modified is used in this article to indicate the Last modification time and the cache is not prohibited.
Header ('Last Modified: Sat, 30 Oct 2010 13:21:21 gmt ');
The page on which the user logs on is prohibited from caching.
Header ('cache-Control: max-age = 0 ');
Header ('cache-Control: private ');

HTTP protocol encoding and mime:
The HTTP output must declare the encoding and mime. There must be a space between charset and semicolon. Lowercase UTF-8 or uppercase UTF-8, not found documentation, to be investigated.
For example
Header ('content-Type: application/json; charset = UTF-8 ');
Header ('content-Type: application/xml; charset = UTF-8 ');
Header ('content-Type: application/xhtml + xml; charset = UTF-8 ');
Header ('content-Type: text/plain; charset = UTF-8 ');
Header ('content-Type: text/html; charset = UTF-8 ');

Case sensitivity:
In categories, functions, file names, directory names, and other places, special nouns are not treated, and full uppercase is not used. Discussion result: lower case is used.
Reason: it is difficult to define the terminology, such as HTML, CSS, and CRUD. In addition, full uppercase leads to conflicts with the hump. For example, the page Assistant class is HTMLHelper, which is better than HtmlHelper.
Special handling is supported:
HTML is a proprietary term, but Content-Type: text/html is used in mime, rather than text/HTML.
Example:
Use UserDb. php instead of UserDB. php.

 

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.