PHP coding track 2

Source: Internet
Author: User
PHP coding specifications 21 Introduction & nbsp; in order to better improve development efficiency and ensure development effectiveness and rationality, this specification is formulated to maximize code readability and reusability. This specification includes PHP coding specification for PHP Development 2
1 Introduction

This specification is formulated to better improve development efficiency, ensure development effectiveness and rationality, and maximize code readability and reusability. This specification includes code indentation rules, control structures, function calls, function definitions, comments, comments containing code, PHP tags, file header comments blocks, CVS tags, and URLs in PHP development. example, constant naming rules.


1.1 Importance of standardization

The standardization problem does give everyone a headache in some aspects, and makes everyone feel that they are in the same situation. But this is often due to misunderstanding of standardization. Standardization is not a constraint. it aims to provide the overall quality and development progress of the project during large-scale development. Some may say, well, I don't like Constraint. doing so will constrain my creativity. If your creativity is only in the naming and format (and this is exactly the main content of the norms), let's discard your creativity. no one will like it.
1.2 Advantages

When a project tries to comply with public standards, it has the following benefits:

· Programmers can understand any code and find out the program status

· Newcomers can quickly adapt to the environment

· Prevent new php contacts from creating a new style and forming a lifelong habit out of time-saving needs

· Prevent new php contacts from making the same mistake again and again

· In a consistent environment, people can reduce their chances of making mistakes.

· Programmers have the same enemy
1.3 improvement

The standards are not static. if you think the standards are missing or inappropriate, you may consider joining them. remember that any project depends on the efforts of the team.
1.4 Implementation

Generally, the implementation of specifications is implemented and supervised by the technical director or project manager. However, the best way is to reach consensus in the development team and become a cultural existence.
2 Naming rules

Naming is the core of program planning. The name is a long-term and profound result of a thing in its ecological environment. In general, only programmers who know the system can obtain the most appropriate name for the system. If all the names are suitable for their nature, the relationship is clear, and the meaning can be deduced. the assumption of the average person can also be expected.
If you find that only a few of your names can match their corresponding items, you 'd better look at your design again.
2.1 file name

File names use the c gnu convention. all letters use lowercase letters and '_' to separate words.

For example:

News_list.php



Some file names are almost common words. for example, the admin prefix indicates that the file name is managed by the background, inc. the php suffix indicates the file or class library file, class. php suffixes indicate class library files and so on. Config. php indicates the configuration file.

For example:

Admin_user.php

Data. inc. php

User. class. php




Class name 2.2

· Use uppercase letters as the separation of words, and use lowercase letters for other letters
· Use uppercase letters for the first letter of the name
· Do not use underscores ('_')
For example
Class NameOneTwo
Class Name



Note:

· Before naming a class, you must first know what it is. If you still cannot think about the class name, your design is not good enough.
· A hybrid name composed of more than three words is easy to cause confusion between various entities of the system. let's look at your design and try to use (CRC Session card) check whether the object corresponding to the name has so many functions.
· The name of a derived class should not be associated with its parent class name. The name of a class is only related to itself and has nothing to do with its parent class name.
· Some extensions are almost conventional. for example, if your system uses an agent, you can name a part as a DownloadAgent) it is used to transmit real information.

Of course, these conventional words will not automatically appear and need to be summarized by the team.


2.2.1 do not use uppercase letters for all acronyms



· In any of the following situations, you can use the upper-case letters and the lower-case letters in the first letter to represent the acronym.
Use: GetHtmlStatistic.
Not used: GetHTMLStatistic.
Reason
· When the name contains acronyms, people seem to have a very different intuition. Unified rules are the best, so that the meaning of the name can be completely pre-known.
Here is an example of NetworkABCKey. it is very confusing to note whether C in ABC or C in key. Some people don't care about this, but others hate it. So you will see different rules in different codes, so that you do not know how to call them.
For example
Class FluidOz // do not write it as FluidOZ
Class GetHtmlStatistic // do not write it as GetHTMLStatistic
2.3 Class Library name



· Namespace is becoming more and more widely used to avoid class name conflicts between different vendors and group class libraries.
· When namespace is not used yet, to avoid class name conflicts, the general practice is to add a unique prefix before the class name so that two characters can be used. of course, it is better to use more.
For example
John Johnson's data structure class library can use Jj as the prefix, as shown below:
Class JjLinkList
{
}
Another compromise is to create a directory containing the class library (in fact, Java does the same). different directories represent different namespaces.
For example
Microsoft database-related class libraries can be found:
/Classes/com/Microsoft/Database/DbConn. php
Apache database-related class libraries can be found in:
/Classes/org/apache/Database/DbConn. php


2.4 Class attribute naming

· Class attributes use the c gnu convention. all letters use lowercase letters and use '_' to separate words.

For example
Class NameOneTwo
{

Function var_abc (){};

Function error_number (){};

Var $ var;

Var $ error_number;

Var $ name;

}


2.5 method naming

· The function name follows the c gnu convention. all letters use lowercase letters and '_' to separate words.

For example
Class NameOneTwo
{

Function do_it (){};

Function handle_error (){};

}



· Every method usually executes an action, so the naming of them should clearly describe what they do: replace error_check () with check_for_errors (), and use dump_data_to_file () replace data_file (). In this way, functions and data can also be differentiated.
· Sometimes suffix names are useful:
O Max-indicates the maximum value that an object can assign.
O Cnt-the current value of a running count variable.
O Key-Key value.
For example, retry_max indicates the maximum number of retries, and retry_cnt indicates the current number of retries.
· Sometimes prefix names are useful:
O Is-it means to ask a question about something. At any time, people will know that this Is a problem.
O Get-indicates obtaining a value.
O Set-meaning to Set a value
For example, is_hit_retry_limit.




2.6 parameter naming in method



· The function name follows the c gnu convention. all letters use lowercase letters and '_' to separate words.



For example
Class NameOneTwo
{

Function start_your_engines (

& $ Some_engine,

& $ Another_engine );

}
2.7 variable naming



· All letters must be in lower case.
· Use '_' as the boundary of each word.
Reason
· In this way, the scope of variables in the code is clear.
· All variables look different in the code and are easy to identify.
For example
Function handle_error ($ errorNumber)
{

$ Error = OsErr ($ errorNumber );

$ Time_of_error = $ error-> get_time_of_error ();

$ Error_processor = $ error-> get_error_processor ();
}


2.8 global constants

· Global constants are separated by '_' and all words are capitalized.

Reason
This is the tradition of naming global constants. Do not conflict with other definitions.
For example
Define ("A_GLOBAL_CONSTANT", "Hello world! ");

2.9 static variables

· Static variables should have the prefix's '.

Reason
· It is very important to know the scope of a variable.
For example
Function test ()
{

Static $ msStatus = 0;

}
2.10 function name



· The function name follows the c gnu convention. all letters use lowercase letters and '_' to separate words.
Reason

· This makes it easier to differentiate associated class names.

For example

Function some_bloody_function ()
{

}


2.11 error return detection rules

· Check all system call errors unless you want to ignore them.
· Define the system error text for each system error message to include.

3 Writing Rules
3.1 braces {}

Two of the three main braces are acceptable, and the first is the best:
· Place braces in the same column below the keywords:

If ($ condition)

{
......
}

While ($ condition)
{
......
}
· The Traditional brackets of UNIX are the same as the keywords. the ending brackets are the same as the keywords:
If ($ condition ){

......

}

While ($ condition ){
......
}

Reason:

Non-principled issues that have aroused heated debate can be solved through a compromise. either of the two methods is acceptable, but most people prefer the first one. The reason is the scope of psychological research.

There are more reasons to prefer the first one. If the character editor you are using supports the bracket matching function (for example, vi), the most important thing is to have a good style. Why? We say that when you have a large program and want to know where it ends. Move the brackets to the beginning, and press the button editor to find the ending brackets. for example:

If ($ very_long_condition & $ second_very_long_condition)
{
...
}
Else if (...)
{
...
}
To move from one block to another, you only need to use the cursor to match your brackets. no matching brackets are needed.

3.2 indent: Tab vs. space

When writing code, you must pay attention to the code indent rules. we stipulate that four spaces are used as indentation, rather than tab indentation (ultraedit can be pre-configured ).

· There is no fixed rule for the maximum number of indentation layers. if the number of indentation layers is greater than four or five layers, you can consider decomposing the code factor (factoring out code ).
Reason
· Many programmers support tabs. However, the number or meaning of spaces represented by the TAB standards varies with programming tools and platforms. This will make the code in good format on one platform unsightly under another platform. For php development, it is usually developed on the win platform and deployed on linux. pay special attention to this issue.
· Although there is no limit on the maximum number of indentation layers, it is generally recommended that the number should not exceed four or five layers.
For example:

Function func ()
{
If (something bad)
{
If (another thing bad)
{
While (more input)
{
}
}
}
}

3.3 parentheses, keywords, and functions

· Do not enclose parentheses and keywords together. separate them with spaces.
· There is no space between the parentheses and the function name. for example, $ test = date ("ymdhis ");
· Do not use parentheses in Return statements unless necessary.
Reason
· The keyword is not a function. If the parentheses closely match the function name and keyword, the two are easily regarded as one.
For example
If (condition)
{
}

While (condition)
{
}

Strcmp ($ s, $ s1 );

Return 1;

Constructor of the 3.4 class

Do not do the actual work in the constructor. The constructor should contain the initialization of variables and (or) will not fail.
Reason
· The constructor cannot return an error.

For example
Class Device
{
Function device () {/* initialize and other stuff */}
Function open () {return FAIL ;}
};

$ Dev = new Device;
If (FAIL = $ dev-> open () exit (1 );


3.5 = Symbol Writing

The = symbol in the program follows the following rules:

(1) leave a space on both sides of the = symbol, such as $ a = $ B and if ($ a = $ B;

(2) in a declarative block or a block implementing the same function, the = sign must be aligned up and down as much as possible. on the left side, multiple spaces can be used to maintain alignment, A space is required on the right side. for example:

$ Testa = $ aaa;

$ Testaa = $ bbb;
3.6 control structure
3.6.1 if then else format

Different curly braces may have slightly different styles. A common method is:
If (condition 1) // comment
{
}
Else if (condition 2) // comment
{
}
Else // annotation
{
}
If you use the else if statement, it is usually better to have an else block to handle other unprocessed situations. If possible, place a record information comment in else, even if there is no action in else.

· Always place the constant value on the left of the equal sign or non-equal sign, for example:
If (6 = $ errorNum )...
One reason is that if you miss an equal sign in the equation, the syntax examiner will report an error for you. The second reason is that you can immediately find a value instead of finding it at the end of your expression. It takes a bit of time to get used to this format, but it is really useful.

3.6.2 switch format

· After a case block is processed, it is directly transferred to the next case block for processing. add comments at the end of the case block.
· The default case should always exist, and it should not be reached. However, if it is reached, an error will be triggered.
· If you want to create a variable, put all the code in the block.
For example
Switch (...)
{
Case 1:
...
// FALL THROUGH
Case 2:
{
$ V = get_week_number ();
...
}
Break;

Default:
}
3.6.3 continue and break

Continue and break are actually concealed goto methods in disguise.
Like goto, continue and break are magical in code, so they should be frugal (as few as possible) to use them. With this simple magic, readers will be directed to places only known to God for some undisclosed reasons.
Continue has two main problems:
· It can bypass test conditions.
· It can bypass other/unequal expressions.
Let's take a look at the example below and consider where the problem occurs:
While (TRUE)
{
...
// A lot of code
...
If (/* some condition */){
Continue;
}
...
// A lot of code
...
If ($ I ++> STOP_VALUE) break;
}
Note: "A lot of code" is required to prevent programmers from easily identifying errors.
Through the above example, we can draw a further rule: the hybrid use of continue and break is the correct method to cause disasters.
3.6.4? :

? : No problem. The problem is that people often try? And: it is full of code. The following are clear connection rules:
· Place conditions in parentheses to separate them from other codes.
· If possible, simple functions can be used for actions.
· Take the action, "?", ":" Is placed on different rows unless they can be clearly placed on the same row.
For example
(Condition )? Funct1 (): func2 ();

Or

(Condition)
? Long statement
: Another long statement;

3.7 Block declaration positioning

· The declared code block must be aligned.
Reason
· Clear.
· List of Code blocks similar to variable initialization.
· & Depends on the near type, rather than the variable name.
For example
Var $ mDate
Var & $ mrDate
Var & $ mrName
Var $ mName

$ MDate = 0;
$ MrDate = NULL;
$ MrName = 0;
$ MName = NULL;
3.8 each line of statements should be as short as possible

Unless these statements are closely related, only one statement is written in each line.

In code writing, follow the following principles:

(1) try to ensure that one line of a program statement is a line, rather than a line of statement that is too long to generate a line;

(2) Try not to make the code of a line too long. generally, it should be controlled within 80 characters;

(3) If a line of code is too long, use a method similar to. = to cut the line of writing;

(4) do not write SQL statements in the function to execute Database SQL statements. Instead, define SQL statements with variables and then call the defined variables in the function that executes the operation;

For example:

$ SQL = "SELECT username, password, address, age, postcode FROM test_t ";

$ SQL. = "WHERE username = 'AAA '";

$ Res = mysql_query ($ SQL );
3.9 short method

The method code must be within one page.
3.10 record all null statements

The for or while empty block statement is always recorded, so that you can clearly know whether the code is missing or intentionally not written.

While ($ dest ++ = $ src ++)
; // VOID

3.11 do not use the default method to test the non-zero value.

Do not use the default value to test the non-zero value, that is, use:

If (FAIL! = F ())
Better than the following method:

If (f ())

Even if FAIL can contain 0 values, PHP considers it false. But when someone decides to use-1 instead of 0 as the return value for failure, an explicit test will help you. Explicit comparison should be used even if the comparison value does not change;

For example:

If (! ($ Bufsize % strlen ($ str )))

It should be written:

If ($ bufsize % strlen ($ str) = 0)

It indicates the value (not Boolean) of the test. A common problem is to use strcmp to test a character equation, and the result will never be equal to the default value.
If a non-zero test is performed based on the default value, other functions or expressions are subject to the following restrictions:
· Only 0 is returned, indicating failure. it cannot be/with other values.
· Naming so that a true return value is absolutely explicit. call the IsValid () function instead of Checkvalid ().

3.12 Boolean logical type

Follow the following rules:

(1) 0/1 cannot be used to replace true/false. in PHP, this is not equal;

(2) do not use a non-zero expression, variable, or method to directly perform true/false judgment, but strictly complete true/false judgment must be used;

For example, if (FALSE) is used instead of if ($ a) or if (checka! = $ A) or if (FALSE! = Check ())




Most functions return 0 when FALSE, but not 0 represents TRUE, so do not use 1 (TRUE, YES, and so on) equality to detect a Boolean value, 0 (FALSE, NO, and so on) inequalities should be used instead:

If (TRUE = func ()){...
It should be written:

If (FALSE! = Func ()){...

3.13 Avoid embedded assignment



Sometimes you can see the embedded value assignment statement. this structure is not readable.

While ($! = ($ C = getchar ()))
{
Process the character
}
++ And -- operators are similar to value assignment statements. Therefore, for many purposes, side effects may occur when using functions. It is possible to use embedded assignment to improve the runtime performance. In any case, when using an embedded value assignment statement, programmers must consider balancing the growth rate and reduced maintainability. For example:

A = B + c;
D = a + r;
Do not write it:

D = (a = B + c) + r;

Although the latter can save a period. However, in the long run, with the increasing maintenance costs of the program, the program writers gradually forget the code and will reduce the optimization gains in maturity.


4. Notes

There are two annotation methods in PHP, one is to start with //, and the other is to use /**/. // It is generally used for brief comments. /**/Is used in code that requires a lot of comments.

Annotations should be as clear and concise as possible. at the same time, after your annotations can be parsed by machines, they can be put into the manual in a fixed format. The main types of annotations include class comments, attribute comments, method comments, variable comments, key algorithms, and important code implementations. All these parts are woven together so that people can know exactly what you have done and why you have done so in the future.

Some predefined keywords are used to indicate the purpose and author of a method during annotation, so that another set of keywords or Chinese pinyin is not needed.

Annotation is a method that increases the readability and maintainability of the program, rather than the only method. Readability and maintainability are mainly improved in code naming and project organization.
4.1 predefined keywords

Keyword meaning
Purpose indicates what the class, attribute, and method will do or what it means.
Package Name class Name
Author of Author
Modifications modification record (the numbering rule is "No" + date + "-" + serial number)
Ref Reference
Method Name
Parameter name (including type)
Return value (including type)
Attribute/Variable Name
Type attribute/variable Type


4.2 File header comments

Each file header must have a uniform comment block. The rules are as follows:

A. The description of this file must be included;

B. The author must be included;

C. The written date must be included;

D. The version information must be included;

E. The project name must be included;

F. The file name must be included;

G. important usage instructions, such as class call methods and precautions;

Example:


//

// + --------------------- +

// | PHP version 4.0 |

// + --------------------- +

// | Copyright (c) 1997-2001 The PHP Group |

// + --------------------- +

// | This source file is subject to of the PHP license, |

// | That is bundled with this packafile LICENSE, and is |

// | Available at through the world-web at |

// | Http://www.php.net/license/2_02.txt. |

// | If you did not receive a copy of the and are unable to |

// | Obtain it through the world-wide-web, end a note to |

// License@php.net so we can mail you a immediately. |

// + --------------------- +

// | Authors: Stig Bakken |

// | Tomas V. V. Cox |

// |

// + --------------------- +

//

// $ Id: Common. php, v 1.8.2.3 2001/11/13 01:26:48 ssb Exp $




Comments of the 4.3 class

Each class annotation must contain the following items:

A. The class description must be included;

B. The author must be included;

C. The written date must be included;

D. The version information must be included;

E. namespace (optional );

F. Reference (optional );

Example:

/**
* @ Purpose:
* Database access class. ODBC is used as the Universal Access interface.
* @ Package Name: Database
* @ Author: Forrest Gump gump@crtvu.edu.cn
* @ Modifications:
* No20020523-100:
* The second and third positions of the odbc_fetch_into () parameters are swapped.
* John Johnson John@crtvu.edu.cn
* @ Ref: (reference)
*/
Class Database
{
......
}

4.4 method comments

Each class annotation must contain the following items:

A. method description is required;

B. The method name must be included;

C. The income parameter and type must be included;

D. The output parameters and types must be included;



Example:

/**
* @ Purpose:
* Execute a query
* @ Method Name: query ()
* @ Parameter: string $ queryStr SQL query string
* @ Return: Return value of the mixed query (result set object)
*/
Function ($ queryStr ){......}

4.5 attribute comments

The property annotation must contain the following items:

A. brief attribute description (required );



Example:

// User name

Var mDbUserName;


4.6 variable comment

The variable annotation must contain the following items:

A. brief description of the variable (optional );



Variables appear the most frequently in the program, and they should be clearly indicated by their names. Annotations can be omitted for temporary variables and variables with narrow Scopes. Otherwise, the program will become very bloated due to annotations.



Example:

// User name

$ User_name;
4.7 code block comments

Code block annotations are used only when necessary, such as key algorithms of programs. The annotation method is the same as the variables and attributes.



Example:



Func f ()

{

... ...

// Bubble sorting is used here

... ...

}


5. Project organization

This section mainly describes the relevant documents, source code, and descriptions at the project level. Depending on the project properties, the following sections can be added or deleted.
5.1 Project structure

· Design documents

It mainly includes software design class diagrams, packet diagrams, database structures, and key algorithm references.

· Project Description

It mainly includes software installation, usage instructions, initial accounts, and precautions to guide people to display resources:

· Source code

Indicates the source code that can be compiled or run normally.

· Project management

Including requirement documents, project management, and Bug fixes.

In addition to the above documents, it may contain other types of documents, which can be archived according to the type defined by the project.
5.2 source code structure

This section describes the frequently used directory names for developing enterprise websites or small websites. Of course, if the project you want to develop is similar to Baidu or Sina, you may not need it because at that time, there will be professional personnel or norms for constraints, and all aspects have been involved. In general, these are still helpful to you.

A complete and independent PHP project directory structure is as follows:

/Project root directory

/Manage (admin) background management file storage directory

/Css file storage directory

/Images path for storing all image files (in which subdirectories are set up based on the directory structure)

/Scripts client js script storage directory

/Tpl website template file storage directory

/Uploads Upload file directory

/Inc (include) global functions include file directories

/Cache Directory

/Install Installer Directory



The preceding directory structure is a common directory structure. you can consider not to follow it completely based on the specific application conditions, but try to standardize it as much as possible.
5.3 Third-party development kit

For third-party development kits introduced during development, if possible, try to put them in a separate directory for management, and add the relevant documentation of the development kit in the project documentation: help documentation, principles, project address.

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.