thinkphp Development Code

Source: Internet
Author: User
Tags naming convention pear script tag

1. Purpose of preparation

???? In order to better improve the efficiency of the technical department, to ensure the effectiveness and rationality of development, and to maximize the readability of the program code and reusable, specify this specification. The development team can supplement or reduce this specification according to its own actual situation.

1, the programmer can understand any code, clarify the status of the program;
2, new people can quickly adapt to the environment;
3, to prevent the new contact PHP people to save time for the need to create a set of style and develop lifelong habits;
4, to prevent new contact with PHP again and again to make the same mistake;
5, in a consistent environment, people can reduce the opportunity to make mistakes;
6, the program members have a consistent enemy;

2. Overall requirements

???? The PHP Development Code of the Ministry of Technology will refer to the specifications of pear, and use the specifications specified by pear to add, modify or delete some of the specifications suitable for the specific development environment. This specification is only for the code in PHP development process, for PHP development project files, directories, databases and other aspects of the specification, will not focus on.

???? This specification contains rules for naming specifications, code indentation rules, control structures, function calls, function definitions, annotations, include code, PHP tags, header comment blocks, CVS tags, url samples, and constant naming in PHP development.

3. Safety specification

???? When we try to code, many times do not know how to make their own code to be safe, because we lack of security knowledge, security common sense of the norms can help you to eliminate some of the daily rookie hacker attacks, but can not prevent the experts of the fierce offensive, so more advanced security we have to learn from other ways.

3.1. Include files

???? The inclusion of PHP files in the introduction of files through PHP functions, because the incoming file name is not properly verified, so that the operation of the unintended files, can lead to accidental file leaks and even malicious code injection.

3.1.1, naming rules

???? Extract the include file with a generic function, file suffix to .inc name it, indicating that it is an include file.
???? If you have more than one .inc file to contain multiple pages, please .inc enclose all the files in a file, specific to the page only need a replacement .inc file on it.

???? such as: xxx_session.inc ,, xxx_comm.inc xxx_setting.inf , myssql_db.inc .
???? The above file is encapsulated in the file in the following way xxx.basic.inc :

require_once(‘xxx_session.inc‘);require_once(‘xxx_comm.inc‘);require_once(‘xxx_setting.inc‘);require_once(‘mysql_db.inc‘);

Note:
Whether it needs to be encapsulated into a file, as the case may inc be, is not recommended if each feature is distributed across different pages.

3.1.2, storage rules

???? The generic include file does not need to be exposed directly to the user, so it should be placed in a Web Server directory that cannot be accessed, to avoid leaking setup information because of configuration issues

3.2. Security rules

???? please refer to the Product safety checklist.

input and output:

Check whether HTML code is being filtered  
Possible problems: If someone enters malicious HTML code, it can result in stealing cookies, generating malicious login forms, and destroying the site.

Check if the variable was done before the database operation escape  
Possible problems: If a string variable to write a query statement contains some special characters, such as quotation marks ( ', ') or a semicolon (;) May cause an operation that is not expected to be performed.  

Recommended method: Use mysql_escape_string () or a function that implements similar functionality.

Check the legality of input values  
Possible problems: The value of the exception is causing the problem. If the input value is not checked, it will cause illegal or incorrect data to be deposited in udb, stored in other databases or cause unexpected program operation to occur.

Example: If the program takes the user input parameter value as the file name, carries on the document operation, the malicious input system file name can cause the system to destroy.

Verify the use of cookies and the processing of user data  
Possible problems: Incorrect cookie usage may result in user data leaks.

access control  
for internally used products or for products used by partners, consider increasing access control.

logs  
Ensure that the user's confidential information is not recorded in log (for example: User's password),  
ensures that a complete user access record is saved for critical user actions.

https  
transfer of sensitive data to HTTPS.

3.3. Some rules for PHP

???? Set register_globals = off ;
???? Set error_reporting = E_ALL , and to fix all the error and warning ;
???? Place the actual action in the referenced file. Place the reference file in a directory that cannot be browsed directly.

register_globalshas been deprecated since PHP 5.3.0 and will be removed from PHP 5.4.0.

3.4. Other processing rules

???? Other processing rules

3.4.1, input parameter processing

???? The SQL operation is required for the page to get the parameter, which needs to be escaped, especially "'".

???? Such as:

$a = ‘ Let’s go ‘ ;$sql = "Insert into tmp(col) values(‘$a‘)";

There is a false uncertainty about this situation.

3.4.2, manipulating large HTML text

???? Many times you need to store a large piece of HTML text for the page to use, such as a user-defined header footer.
???? You need to remove the script tag to avoid executing malicious PHP code.
???? Convert "<" ">" to guarantee the full text of the code HTML .

4. Code specification

???? Normalize code files and code.

4.1. Naming specification

???? The development of a unified naming standard for the project is very important, not only can develop a good programmer development habits, but also to increase the readability of the program, portability and reusability, but also to improve the efficiency of project development.

1. Common variables

Common variable naming follows these rules:
???? A All letters are used in lowercase;
???? b For a variable that uses multiple words, use the _ interval as each word.

For example: $base_dir , and $red_rose_price so on.

2. Static Variables
Static variable naming follows these rules:
???? A Static variables are prefaced with lowercase s_ ;
???? b Static variable all letters are lowercase;
???? C Multiple words consist of variable names _ that are used as intervals for each word.

Examples: $s_base_dir , and $s_red_rose_prise so on.

3. Local Variables
Local variable naming follows these rules:
???? A Use lowercase for all letters;
???? b The variable uses the _ beginning;
???? C A local variable name consisting of multiple words is used _ as the interval between each word.

Examples: $_base_dir , and $_red_rose_price so on.

4. Global Variables
Global variables should be prefixed with G_ all uppercase letters, and it is important to know the scope of a variable. For example:

global $G_LOG_LEVEL;global $G_LOG_PATH;

5. Global Constants
Global variable naming follows these rules:
???? A All letters use uppercase;
???? b Global variables are used as intervals between multiple words _ .
Example:

define(‘BASE_DIR‘,‘/base/dir/‘);define(‘RED_ROSE_PRICE‘,20.0);

6.session Variables
Session variable naming follows these rules:
???? A All letters use uppercase;
???? b The session variable name uses the S_ beginning;
???? C Use intervals between multiple words _ .

Examples: $S_BASE_DIR , and $S_RED_ROSE_PRICE so on.

4.1.2, class naming

Class naming in PHP follows these rules:
???? A Start with a capital letter;
???? b A variable name consisting of multiple words, with no spacing between words, capitalized on the first letter of each word.

Example: class MyClass or class DbOracle so on.

4.1.3, method, or function

method or function naming follows these rules:
???? A First letter lowercase;
???? b No interval is used between multiple words, except for the first word, and the first letter of the other word is capitalized.

Example: function myFunction() or function myDbOracle() so on.

4.1.4, abbreviated words

When an abbreviation is encountered in a variable name or other naming, refer to the specific naming convention instead of using the original capitalization of the abbreviation.

Example: function myPear (not mypear) functio getHtmlSource (not gethtmlsource).

4.1.5, database table name

database table name naming follows these specifications:
???? A The table names are in lowercase letters;
???? b For a normal data table, use the _t end;
???? C For the view, use the _v end;
???? D For table names consisting of multiple words, use _ interval;

Examples: user_info_t and book_store_v so on.

4.1.6, database fields

database field naming follows these specifications:
???? A all use lowercase;
???? b Use intervals between multiple words _ .

Examples: user_name , and rose_price so on.

4.2. Writing Rules

Writing rules refer to the rules of code writing when writing PHP programs, including indentation, structure control, and so on.

4.2.1, Code indentation

In writing the code, you must pay attention to the code indentation rules, we stipulate that the code indentation rules are as follows:
???? A Use 4 spaces as indents without using the tab indent (for ultraedit , you can preset them).

Example:

for ( $i=0;$i<$count;$i++ ) {    echo ‘test‘;}
4.2.2, curly braces {} writing rules

In the program to write structure control code, such as,, if for , and while switch other structures, braces traditionally have two writing habits, respectively, are as follows:
???? A {directly following the control statement, do not wrap, such as:

for ( $i=0;$i<$count;$i++ ) {    echo ‘test‘;}

???? b The { next line in the control statement, such as:

for ( $i=0;$<$count;$i++ ){    echo ‘test‘;}

???? Among them, A is PEAR the recommended way, but from the actual writing, this does not affect the program's specification and impact with the phpdoc implementation of the document, so can be based on personal habits to adopt the above two ways, but requires in the same program, only one of the use, in order to avoid the inconvenience of reading.

4.2.3, parentheses () and functions, keywords, etc.

Parentheses, keywords, and functions follow these rules:
???? A Do not put parentheses and keywords close together, to use a space interval; if ( $a<$b )
???? b No spaces between parentheses and function names; $test = date("ymdhis")
???? C Do not Return use parentheses in the return statement unless necessary. such as Return $a ;

4.2.4, = symbol writing

The = writing of symbols in a program follows the following rules:
???? A On = Both sides of the symbol, a space shall be left; $a = $b $a = ‘test‘
???? b In the = symbol and,, ! , and = < > other symbols adjacent, do not need to leave a space; if ( $a == $b ) if ( $a != $b )
???? C In a declaration block, or to achieve the same function in a block, the requirement = number as far as possible to it, the left can be used to maintain the alignment of multiple spaces, and the right requires a blank space;

$testa   = $aaa;$testaa  = $bbb;$testaaa = $ccc;
4.2.5, if else swith for while etc. writing

The writing for the control structure follows these rules:
???? A In if conditional judgment, if a constant is used to determine the condition, the constant is placed on the left side of an equal sign or an equal sign, for example: if ( 6 == $errorNum ) because if you miss an equal sign in the equation, the grammar checker will give you an error, you can quickly find the wrong position, such a way to pay attention to;
???? b switchthere must be a block in the structure default ;
???? C In for the wiile circulation of and use, to be vigilant continue , break use, to avoid goto the emergence of similar problems;

 Constructors for 4.2.6 and classes

If you want to write a constructor inside a class, you must follow these rules:
???? A You cannot have too many actual operations in the constructor, at most, to initialize some values and variables;
???? b You cannot return or error in a constructor because you false are using an operation, because you cannot return an error when declaring and instantiating an object;

4.2.7, sentence break

In code writing, follow these guidelines:
???? A Try to ensure that the program statement line is a sentence, and do not let a line of statements too long to produce a folded line;
???? b Try not to make a line of code too long, generally control within 120 characters;
???? C If one line of code is too long, use a similar way to break .= the lines;
???? D For a statement operation that executes a database, sql try not to write the statement inside the function, sql but first define the statement with the variable and sql then invoke the defined variable in the function that performs the operation;

Example:

$sql = ‘SELECT username,password,address,age,postcode FROM test_t ‘;$sql .= ‘ WHERE username=\‘aaa\‘‘;$res = mysql_query($sql);
4.2.8, Digital

A naked number used in the source code is an incredible number, because the author, within three months, no one knows what it means. For example:

if ( 22 == $foo ) {    start_thermo_nuclear_war();} elseif ( 19 == $foo){    refund_lotso_money();} else {    cry_cause_in_lost();}

You should use it to define() give you a real name for the value you want to represent something, not a naked number, for example:

define(‘PRESIDENT_WENT_CRAZY‘, ‘22‘);define(‘WE_GOOFED‘, ‘19‘);define(‘THEY_DIDNT_PAY‘, ‘16‘);if ( PRESIDENT_WENT_CRAZY == $foo ) {    start_thermo_nuclear_war();} elseif ( WE_GOOFED == $foo){    refund_lotso_money();} elseif ( THEY_DIDNT_PAY == $foo ){    infinite_loop();} else {    cry_cause_in_lost();}

4.2.9, judging

Follow these rules:
???? A Can not be used 1/0 instead true/false , in PHP, this is not equal;
???? b Do not use non-zero expressions, variables or methods to true/false judge directly, but must use strict complete true/false judgment;

Such as: Not used if ( $a ) or if ( checka() ) used if ( FALSE != $a ) or if ( FALSE != check() ) .

4.2.10, avoid embedding assignments

Avoid the embedded assignment in the following example in the program:
Do not use such a way:

while ( $a != ( $c = getchar() ) ) {    process the character}

4.2.11, error return detection rule

Check all system calls for error messages unless you want to ignore the errors.

The system error text is defined for each system error message and an error is logged LOG .

4.3. Program notes

Each program must provide the necessary comments, write the annotation requirements Specification, reference PEAR the provided annotation requirements, and prepare for future use of the phpdoc generated PHP document.
The principles of program annotations are as follows:
???? A Note In addition to the comment block of the header of the file, the comment is not used elsewhere // /* */ ;
???? b Note Content must be written in front of the annotated object, not written in one line or behind;

4.3.1, program header comment Block

Each program head must have a uniform comment block, the following rules:
???? A Must contain a description of the program;
???? b must include the author;
???? C must contain written date;
???? D must contain version information;
???? E Must include the project name;
???? F Must include the name of the file;
???? G Important usage instructions, such as the invocation method of the class, precautions, etc.;

Reference examples are as follows:

//// +---------------------------------------------------------+// | 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// | [email protected] 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 for 4.3.2, classes

The comments for the class are in the reference example:

/** * @ Purpose: * 访问数据库的类,以ODBC作为通用访问接口 * @Package Name: Database * @Author: Forrest Gump [email protected] * @Modifications: * No20020523-100: * odbc_fetch_into()参数位置第二和第三个位置调换 * John Johnson [email protected] * @See: (参照) */class Database {    ...}
Annotations for 4.3.3, functions, and methods

Comments on functions and methods are written in front of the function and method, using a rule similar to the following example:

/** * @Purpose: * 执行一次查询 * @Method Name: query() * * @Param: string $queryStr SQL查询字符串 * @Param: string $username 用户名 * * @Author: Michael Lee * * @Return: mixed 查询返回值(结果集对象) */function query ( $queryStr, $username ) {    ...}
4.3.4, variable, or statement comment

Comments on variables or statements in the program follow these guidelines:
???? A Write in the front line of a variable or statement, not in the peer or behind;
???? b /* */the manner in which the annotations are used;
???? C A comment block is included in front of each function. The contents include function summary, input/output parameters, expected return value, error code definition;
???? D Note the complete specification;
???? E Delete the commented out code, or note that the commented out code remains in the source for a special reason.

Example:

/** * @Purpose: * 数据库连接用户名 * @Attribute/Variable Name: db_user_name * @Type: string */var db_user_name;
4.4, other specifications 4.4.1, PHP code tags

All PHP program code block tags are used <?php without the use of short tags <? .

4.4.2, program file name, directory name

Both the program file name and the directory name are named in a meaningful English way, with no pinyin or meaningless letters, and must use lowercase letters and intervals between multiple words _ .

4.4.3, PHP project common file directory structure

It is recommended to use the canonical file directory structure when developing a separate PHP project for the specification, which helps to rationalize the logical structure of the project, as well as scaling and collaboration, and team development.

A complete standalone PHP project typically has the following file and directory structure:
/Project root directory
/manageBackground Management file directory
/cssCSS File storage directory
/docStoring project documents
/imagesAll picture file storage paths (in which subdirectories are created according to the directory structure)
/scriptsClient JS Script Storage directory
/tplWeb site All HTML template file storage directory
/error.phpError handling file (can be defined in Apache error handling)
The above directory structure is the usual directory structure, depending on the specific application of the situation, you can consider not to fully follow, but as far as possible to standardize.

Separation of 4.4.4, PHP, and HTML code

???? For projects and applications where performance requirements are not very high, we recommend that you do not write code in a way that is directly mixed with PHP and HTML code, but in a way that is separated by PHP and HTML code, that is, in the form of a template, so that the logical structure of the program is more clear and advantageous, but also helps in the development process Personnel Division , and it also provides more convenience for future project pages to be upgraded to this edition.

For some special cases, such as applications with high performance requirements, you can not use the template mode.

The program logic structure in 4.4.5 and PHP project development

???? For PHP project development, as far as possible to use OOP the idea of development, especially after the PHP5, for the object-oriented development features greatly improved.

???? In the PHP project, we recommend that the standalone function module be written as a function call, corresponding to a whole block of business logic, and we recommend encapsulation into classes that can improve code readability and code reusability. For example, we usually encapsulate the interface of the database into a database class, which facilitates the porting of the platform.

???? Duplicate code is made into a common library. (in addition to our plug-in products, the product family has a number of similar products, in order to minimize the size of the installation package, it is not suitable for these products to share all the functions of the public Library)

5. Special specification of PHP code in specific environment 5.1, variable definition

???? The PHP code in the XXX environment requires all variables to be declared after use, otherwise there will be error messages, for arrays, in the use of an indeterminate key , such as the first isset() judgment, and then use, such as the following code:

$array = array();$var = isset( $array[3] ) ? $array[3] : ‘‘;

5.2. Use of references

???? Reference in the program used more, in order to common the same memory, without the need for additional replication, the use of references in the XXX environment, you need to pay attention to the following situation;

???? When using references to the input parameters of a function, it is not possible to add a reference to the input parameter at the time of the call, & but to use the variable directly, and to indicate that the input parameters are derived from the reference at the time of the function definition, such as the following code:

$a = 1;function ab( &$var ) {    $var ++;    return $var;}$b = ab($a); // 注意,此处不能使用 $b = ab(&$a)的方式;echo $b."\n";echo $a."\n";

At this time $a and $b both are 2;
The special requirements for references in the XXX environment originate from the item settings in the file, which php.ini allow_call_time_pass_reference is publicly On available, so that it is possible to support & to refer directly to the variable before the call function, but this method is protested and may no longer be supported in future versions PHP/Zend . Encouraged to specify which parameters are passed by reference in the function declaration. You are encouraged to try to close this option (using off , all running environments of XXX off ) and confirm that your scripts are still working, to ensure that they will still work in future versions of the language.

5.3. Input and output of variables

???? In the XXX environment, the web through GET or POST method to pass the parameters are required strict filtering and legality verification, not recommended to use direct $_GET , or to $_POST _REQUEST obtain, and through the XXX Xxx_yiv module provides methods to obtain and filter Processing.

thinkphp Development Code

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.