"Go" PHP writing specification PHP Coding standard

Source: Internet
Author: User
Tags autoload coding standards
Transfer from: PHP writing specification PHP Coding standard

PHP Writing specification
Author: sink
Last modified: 2011-7-13

Resources:
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

When formulating the specification, pay attention to:
1, generally do not appear 2 are the case.
For example, tab and 4 spaces are all lines, resulting in code confusion.

General principles:
1, the Semantics of
When you see a name, you know what it means.

2. Universal Prefix
Is indicates whether, get represents read, and set represents write. is followed by the adjective, not the noun, such as whether multilingual, should use is_multilingual, rather than is_multilanguage.

3. Singular and plural
Refer to the function naming rules of JS: getElementById, getElementsByTagName, Getelementsbyname.
For example:
Take the names of my multiple friends and use Getfriendsname instead of getfriendnames or getfriendname
Take a user, is GetUser
Take multiple users, is getusers

4. Redundant suffix
Try not to use the data, list, and info suffixes unless otherwise specified.
For example, the naming of JS is very careful, use getElementsByTagName instead of getelementsinfobytagname.
You should use Getfriends or getfriendsuserid instead of getfriendslist; you should use GetUser instead of GetUserInfo or getuserdata.
However, sometimes it is difficult to avoid, for example, there are 2 functions, which are the basic information of the user, and the user details are taken.
Basic information of User: Nickname, Avatar Uri, function name Getuserbasic or Getuserbasicinfo? The function name does not feel right at the end of the adjective. Pending discussion. Discussion result: getuserbasicinfo suitable.
Take user details: Nickname, Avatar Uri, signature, birthday, function name GetUser no problem.

5, ambiguous meaning of the class name, file name, directory name
Whenever using common, util, functions, Class, Object, basic as the file name to be cautious, because these words are too general, the development of things may be more and more, into the garbage box. To give these an accurate name, for example, to do string processing class, can be called stringlib.php, placed in the Lib directory.

6. The difference between Lib, plugin and addon
Some classes, functions are counted as LIB, plugin or addon. Pending discussion. Discussion result: At present, the enhancement function is LIB, then consider plugin and addon later.

7. Common Vocabulary
The URI is preferred instead of the URL. Because more rigorous, the new naming begins with the URI. For example JS of encodeuri,php's $_server[' Request_uri '.
Deadline and Ttl:deadline indicate the last moment, TTL indicates the time of survival. For example, the current time is 1310449710,ttl is 60 seconds, then deadline is 1310449710 + 60 = 1310449770.

Class Name:
Capital letters start with the hump named. Nouns are commonly used, such as configuring parsing classes Configparser, rather than parseconfig.
Consistent with Java, C + +.
Example: Class Usermodel

The file name of the class:
Same as the class name. This is related to PHP autoload, in order to AutoLoad, the class name is always very long. Pending discussion. Discussion result: Obey Hump, also can realize automatic class loading.
Consistent with Java.
For example, the file name of Class Usermodel is usermodel.php

Non-class file name:
All lowercase, underline-delimited, and no spaces are allowed. Like get_user.php.

Directory Name:
All lowercase, underline-delimited, and no spaces are allowed. such as model, www.

Name of function:
Lowercase letters start with the hump named, for example: function Addblog ().
Consistent with Java, C + +.
functions represent functions, i.e. actions, so verbs are preferred, such as using Editblog instead of Blogedit.
PHP built-in functions for historical reasons, there are many styles, do_something,something_do,dosomething, compared to the new function with the dosomething, only with the current mainstream language consistent.
For example: Paser_str, Json_encode, substr, Fetchall.
Historical reasons may not change, but we can guarantee that the new code is rigorous, and don't let yourself be a historical cause.

Functions in the class:
Two empty rows in the middle of the function. If there is time, the functions are sorted alphabetically, lest it be too confusing.
For example:
Class Blogmodel
{
Public Function Addblog ()
{

}

Public Function Updateblog ()
{

}
}

File Comments:
Comments follow Format according to Phpdoc requirements: http://manual.phpdoc.org/HTMLframesConverter/default/phpDocumentor/tutorial_tags.author.pkg.html
/**
* Blog of various business: Add, update
* @author Sink
*
*/
Class Blogmodel
{

}
?>

API notes:
Be sure to write the input parameters, and the output format. Write clearly what is output when it is correct, and what is output when the error occurs.
Otherwise no one else can use it.

Function Comment:
Be sure to write the output format. Write clearly what is output when it is correct, and what is output when the error occurs.
If the input parameters are complex, include the array, see the parameters can not be seen at a glance, then write the input parameter comments.
There cannot be a blank line between a document comment and a function.
If the steps inside the function are complex, you need to write an in-line comment.
For example:
/**
* Update Blog
* @param int $id blog_id
* @param array $data Array (
"Content" = "" ",//Contents
"Tags" = "" ",//tags
"Update_time" = "" ",//Update time
)
* @return BOOL
*/
Public Function Updateblog ($id, $data)
{
Step1//First step: asdf
Step2//Second step: Qwer
}

Uri:
According to the provisions of RFC1034 International standard, the domain name is forbidden to appear the underscore "_", the domain name is not case-sensitive.
For example, http://dl_dir.qq.com/is the wrong domain name.
Http://example.com is the same as Http://EXAMPLE.COM.
So precedence is used in the URI with all lowercase, get's name lowercase, except for the get value.
Like what
Http://www.google.com/?hl=zh-CN
Http://www.google.com/?hl=zh-cn
The abbreviation for the proper noun of the non-parameter of the URI is used in lowercase and is disputed.
Like what
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 literal code is a proper noun, the ISO must be a minus sign, and the recommended area is capitalized.
The usage of Fedora is strange, using the zh_cn that you make, not ZH-CN. It is also not recommended to use underscores in URIs.
The wiki was lowercase, Google capitalized, and Microsoft used lowercase.

Use the minus sign "-" instead of the underscore in the URI, except for the name of get.
Like what
Http://example.com/1-2-2
Http://example.com/?user_id=123
If you want the user to enter the URI manually, do not distinguish between case and lowercase, because user input is more convenient.
The reality is that users typically enter the domain name manually without entering the URI manually because the URI is very long. In this case, if the URI lowercase is meaningful, if you use http://example.com/?userId=123, the variable name can use the hump $userid = $_get[' userId '), it will be consistent with Java, C + +, So the database will also have to name the hump. Pending discussion. Discussion results: Using the user_id=123.

Variable:
All lowercase, underline delimited, for example: $user _id.
Inconsistent with Java, C + +. Discussion result: use of $user_id.
The member variables of the class, the formal parameters of the function, and the class are instantiated into an object, respecting the naming conventions of the variables.
Reason: URI, database has lowercase convention, get parameters from $_get, $_post, so use lowercase.
PHP built-in variables $_get, $_post use underscores to start with, all caps. No matter how important a custom variable is, don't start with an underscore to avoid future conflicts with built-in variables.
For example: Do not use $_put, $_delete.

Constant:
All uppercase, underline delimited. For example: const MEMCACHE_TTL = 600;

PHP Short Tags:
Use , do not use short labels 。 Because it conflicts with XML and is not conducive to deployment.

Class curly Braces Wrap:
You can take a single line of curly braces, or you can put curly braces on one line with the other, and there is no conclusive argument, pending discussion. Discussion result: Use "peers".
Class Usermodel {

}
Support changer:
http://www.php.net/manual/zh/language.oop5.basic.php
http://pear.php.net/manual/en/standards.classdef.php

function Curly Brace Wrap:
There is no conclusive dispute, pending discussion. Discussion result: Use "peers".
function GetUser () {

}
Support changer:
http://www.php.net/manual/zh/language.oop5.basic.php
http://pear.php.net/manual/en/standards.funcdef.php

If curly braces wrap:
There is no conclusive dispute, pending discussion. Discussion result: Use "peers".
For example:
if (!empty ($name))
{

}
Or
if (!empty ($name)) {//OK

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

Supported by:
http://www.php.net/manual/zh/language.oop5.basic.php
http://pear.php.net/manual/en/standards.control.php

Switch Curly brace Wrap:
Discussion result: Use "peers".
Switch (...) {
Case 1:
...
Break

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

Array parentheses Wrap:
There is no conclusive dispute. Discussion result: Use "peers".
$user = Array (
"id" = "123",
"Name" = "User1",
"Email" = "a@example.com",
)
Supported by:
http://pear.php.net/manual/en/standards.arrays.php

Line wrap Inside Array:
An array of 2-D and more arrays is wrapped inside a line.
Such as
$user = Array (
' id ' = ' 123 ',
' Name ' = ' user1 ',
' Email ' = ' a@example.com ',
);
1-D arrays do not wrap inside. Discussion Result: 1-D arrays are not wrapped inside.
Such as
$users _id = Array (' 23 ', ' 12 ', ' 24 ');//OK

The last comma of the array:
Each row of the array should have a comma at the end so that it is easy to add later. However, the front-end JSON can not have commas at the end, or some browsers do not support, pending discussion. Discussion result: All is OK, because backend does not consider IE front-end.
Like what
$user = Array (
' id ' = ' 123 ',
' Name ' = ' user1 ',//All lines, Pros: Large arrays, often add a row, convenient. If you don't have a comma, it's really hard to add.
);
$user = Array (
' id ' = ' 123 ',
' Name ' = ' user1 '//Both, Pros: rigorous, comma-delimited, the last one does not need to be delimited.
);

Single and double quotation marks:
Use single quotation marks first, and double quotes when escaping is required, and the variables are not enclosed in double quotes. This is different from JSON, where JSON is all double quotes and is discussed. Discussion result: Use single quotation marks preferentially.
Like what:
Echo ' name is: '. $name. '.' . "\ n";
$user = Array (
' id ' = ' 123 ',
);

Condition-judged curly braces:
You must have curly braces, even if there is only one row.
That's right:
if (!empty ($name)) {
DoSomething ();
}
Error:
if (!empty ($name))
DoSomething ();

Carriage return line break:
Use the line-wrap 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

Coding:
Use UTF-8 no BOM. You must not use Windows Notepad to save, because Notepad is UTF-8 BOM cr+lf.
Eclipse?? "Workspace?" "Text file encoding?? "Other:utf-8

Indent:
Use 4 spaces to indent, or you can indent with tab. Discussion result: 4 spaces.
Support 4 Spaces://OK
http://www.oracle.com/technetwork/java/codeconventions-136091.html#262

2 spaces Supported:
Http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Spaces_vs._Tabs

Support for 3, 4 or 8 spaces:
Http://www.possibility.com/Cpp/CppCodingStandard.html#indent

To ensure that the indentation is correct, if you use 4 spaces, you must not appear 5 spaces 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 article uses last modified to indicate the final modification time and does not prohibit caching.
Header (' Last Modified:sat, Oct 13:21:21 GMT ');
A page that requires a user to log on and disables caching.
Header (' cache-control:max-age=0 ');
Header (' cache-control:private ');

HTTP protocol encoding and MIME:
HTTP output must be declared encoded with MIME. There is a space between the charset and the semicolon. lowercase utf-8 or uppercase UTF-8, the document has not been found, pending investigation.
Like what
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 ');

Proper noun case:
In various places, such as classes, functions, filenames, directory names, and so on, no special nouns are treated, and all capitals are not used. Discussion result: use lowercase.
Reason: The proper noun is difficult to define, such as HTML, CSS, CRUD. and full capitalization causes conflicts with the hump, such as the page helper class, all caps are htmlhelper, rather than htmlhelper.
Support for non-special handling:
HTML is a proper noun, but content-type:text/html is used in mime instead of 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.