PHP Coding specification in PHPCMS development documentation

Source: Internet
Author: User
Tags empty expression function definition mysql mysql version sort split dreamweaver
Note: This is the code specification from the PHPCMS development document, although the development specification is called PHPCMS, but I think all PHP programming should be so. Write so much php, a lot of coding compared to this specification is a lot of lack of, in the future must be compared to correct.

PHPCMS encoding Specification
1. Introduction .... 2
2. Applicable scope .... 2
3. The importance and benefits of standardization .... 3
4. PHP Coding specifications and principles .... 3
4.1. Code tags ... 3
4.2. Note ... 3
4.3. Writing rules ... 4
4.3.1. Indent ... 4
4.3.2. Curly braces {}, if and switch. 4
4.3.3. Operators, parentheses, spaces, keywords, and functions ... 5
4.3.4. function definition ... 6
4.3.5. Quotes ... 6
4.3.6. Multi-language problem ... 7
4.4. Naming principle ... 8
4.4.1. Variable, object, function name ... 8
4.4.2. Constant ... 8
4.5. Initialization and logic checking of variables ... 8
4.6. Security ... 9
4.7. Compatibility ... 9
4.8. Code reuse ... Ten
4.9. Other details ... Ten
4.9.1. Include call ...
4.9.2. Error Reporting level ... One
5. Database design .... One
5.1. Field ... One-by-one
5.1.1. table and field naming ... One-by-one
5.1.2. Field structure ... One
5.2. SQL statement ...
5.3. Performance and efficiency ...
5.3.1. Fixed-length and variable-length table ...
5.3.2. Operation and Retrieval ...
5.3.3. Structural optimization and index optimization ...
5.3.4. Query optimization ...
5.3.5. Compatibility issues ...
6. Template design ....
6.1. Code tags ...
6.2. Writing rules ...
6.2.1. Html.
6.2.2. Variable ...
6.2.3. Language elements ...
6.2.4 ... indentation ...
7. Files and directories ....
7.1. File name ...
7.2. Directory naming ...
7.3. Empty Directory Index ...

1. Introduction
This specification, which is composed of programming principles, blends and refines the mature experience that developers have accumulated over a long period of time, and is intended to help form a good and consistent programming style. To achieve a multiplier effect, if necessary this document will be updated irregularly.
Copyright: Shaanxi Jiu-LU Network Technology Co., Ltd., all rights reserved
Last modified: November 20 2006

2. Scope of application
In the absence of special instructions, the following rules are required to be fully applicable to the PHPCMS project and are also applicable to most of the company's other PHP projects.

3. Importance and benefits of standardization
When a software project tries to comply with common standards, it makes it easier for developers involved in the project to understand the code in the project, and to clarify the status of the program. So that new players can quickly adapt to the environment, to prevent some participants from the need to save time, create a style and develop a lifelong habit, resulting in other people in the reading of waste too much time and energy. And in a consistent environment, you can also reduce the chance of coding errors. The flaw is because everyone's standard is different, so need a period of time to adapt and change their coding style, temporary drop bottom of the work efficiency. It is worthwhile to consider a temporary reduction in productivity from the development of the long-term health of the project and the higher efficiency of the team in the later period, which is a process that must be passed. Standards are not the key to the success of a project, but they can help us to be more efficient in team work and more successful in accomplishing our assigned tasks.
1. Programmers can understand any code and find out the status of the program
2. Newcomers can quickly adapt to the environment
3. Prevent new contacts with PHP from the need to save time, create a style and develop a lifelong habit
4. Prevent new contact with PHP people make the same mistake again and again
5. In a consistent environment, people can reduce the chance of making mistakes
6. Programmers have a consistent enemy

4. PHP Coding Specifications and principles

4.1. Code tags
PHP programs can use or to define the PHP code, the HTML page embedded in the pure variable, you can use this form.
In recent years, the PHP development group has been advocating code standardization and standardization, the future version of PHP may start not recommended to use or even cancel and this shorthand form, so in order to enhance program compatibility, before the release we will unify

4.2. Note
Annotations Add short introductory content to code that is easy to forget. Please use the C-style annotation "/* *" and the standard C + + annotation "//".

There are some temporary code and debugging code that must be added to the program development to avoid future oblivion. For all the temporary, debug, and Experimental code, you must add a unified annotation tag "//debug" followed by complete annotation information, so that you can easily check whether there are any questionable code in the program before the program is published and eventually debugged. For example:
$num = 1;
$flag = TRUE; Debug here is not sure if you need to assign a value to $flag
if (empty ($flag)) {

4.3. Rules of writing

4.3.1. Indentation
The Unit convention for each indentation is a tab (8 blank character widths), and each developer involved in the project is forced to set up in the editor (UltraEdit, EditPlus, Zend Studio, and so on) to prevent the formatting from being forgotten when the code is written.
This indentation specification is applicable to functions, classes, logical structures, loops, and so on in PHP and JavaScript.

4.3.2. Curly braces {}, if, and switch
parentheses are peers with keywords, and the parentheses are in the same column as the keywords; in the
if structure, if and ElseIf are peers with two parentheses, one space, and all curly braces are separate lines. In addition, even if there is only one line of statements after if, you still need to add braces to ensure the structure is clear; in a
switch structure, a case block is typically skipped after the processing of a block of cases, so most of the time you need to add a break. The location of the break depends on the program logic, with the case on one line, or a new line, but the position format of the break should be consistent in the same switch.
The following are examples of compliance with the above specification:
If ($condition)
switch ($var)
Case 1:echo ' var are 1 '; break;
2:echo ' Var is 2 '; Break
Default:echo ' var is neither 1 or 2 ';
switch ($str)
case ' abc ':
$result = ' abc ';
$resu lt = ' unknown ';

4.3.3. Operators, parentheses, spaces, keywords, and functions
Each operator has a space between the value or expression that participates in the operation on both sides, and the only special case is the character concatenation operation symbol with no spaces on either side;
The left parenthesis "(" should be attached to the function keyword, in addition to the "(") should be used to separate "(") with the previous content;
Closing parenthesis ")" except for the following "") "or". " , others are separated by spaces;
In addition to the string of deliberately required, in general, in the program and HTML does not appear two consecutive spaces;
In any case, a blank line with a tab or a space cannot appear in a PHP program, i.e., such blank lines should not contain any tab or space. Also, no extra tab or space can appear at the end of any program line. Most editors have the function of automatically removing the trailing space, if the habit is not good, it can be used temporarily, avoid extra space to produce;
For each larger program body, a blank line should be added to the top and bottom, with only 1 blank rows between two blocks, and multiple rows prohibited.
The partition of the program block is as reasonable as possible, too large or too small segmentation will affect others to read and understand the code. Generally, it can be divided into large function definition, logical structure and functional structure. Less than 15 lines of the program block, can not add up and down blank lines;
In the description or display section, content such as Chinese, digital, English words mixed, should be in the number or English words before and after adding spaces.

According to the above principles, the following examples illustrate the correct writing format:
$result = (($a + 1) * 3/2 + $num)). ' Test ';
$condition? Func1 ($var): Func2 ($var);
$condition? $long _statement
: $another _long_statement;
if ($flag)

More than lines
ShowMessage (' Please use the restore.php tool to recover the data. ’);

4.3.4. function definition
The name of the L parameter is consistent with the naming specification of the variable;
L The left parenthesis in the function definition is close to the function name, without space in the middle;
L Start with a left curly brace in another row;
L A parameter with a default value should be at the back of the argument list;
L function call with the definition of the time between parameters and parameters to add a space;
L must carefully examine and eliminate the phenomenon that the starting indent position of the function is different from the ending indent position.

For example, conform to the standard definition:
function Authcode ($string, $operation, $key = ')
if ($flag)
function body

Not conforming to the standard definition:
function Authcode ($string, $operation, $key = ') {
function body

in PHP, single and double quotes have different meanings, the biggest differences are as follows:
single quotes, any variable ($var), special escape characters (such as "\ \ r \ n", and so on) are not resolved, so PHP is faster to parse, and the escape character only supports " \ "" and "\" to escape the single quotes and the backslash itself; in
double quotes, the value of a variable ($var) is replaced in a string, and special escape characters are parsed into a specific single character, as well as special functional escapes specifically for both of these attributes, such as "\$" and "{$array" Key ']}. In this way, although the program is more convenient to write, but at the same time the parsing of PHP is also very slow;
in an array, if the subscript is not an integer, but a string type, be sure to enclose the subscript in single quotes, correctly written as $array[' key ', not $array[key], Because the incorrect writing will make the PHP parser that the key is a constant, and then determine whether a constant exists, not exist only with "key" as the subscript into the expression, while starting error events, resulting in a notice-level error.
Therefore, the use of double quotes is prohibited in the vast majority of cases where single quotes can be used. Based on the above analysis, cases where single quotes can or must be used include but are not limited to the following: the
L string is a fixed value, does not contain special escape characters such as "\ T",
a fixed subscript for an array of l arrays, such as $array[' key ']; string = ' test '; instead of $string = ' test$var ';
exceptionally, in regular expressions (for Preg_ series functions and Ereg series functions), phpcms all use double quotes for the convenience of manual analysis and writing. and maintain the unity of regular expression, reduce unnecessary analysis confusion.
in a database SQL statement, all data must not be enclosed in single quotes, but the intval function should be processed before the SQL query is made, and all strings must be enclosed in single quotes to avoid possible injection vulnerabilities and SQL errors. The correct wording is:
$catid = Intval ($catid);
SELECT * from Phpcms_member WHERE username= ' $_username ' and catid= $catid;

All data needs to be addslashes () before it is inserted into the database, so that special characters are not escaped and an error occurs when inserting the database. If file has been introduced in phpcms, all variables obtained via GET, POST, file, are escaped by default using Addslashes () and do not have to be repeated. If data processing is necessary (for example, for direct display), you can use Stripslashes () recovery, but the data must be escaped again before inserting the database.
In a cached file, the value of the cached data is generally escaped by using addcslashes ($string, ' \ \ \ \ ').


4.4. Nomenclature principle
Naming is the core of program planning. The ancients believed that as long as they knew a person's real name, they would gain an incredible power over that person. As long as you think of the right name, it will give you and later people a stronger power than the code.
A name is a long and far-reaching result in the ecological environment in which things are in place. In general, only programmers who know the system can get the most appropriate name for the system. If all the names are appropriate to their nature, then the relationship is clear, the meaning can be deduced, the average person's supposition can be expected.
In terms of general conventions, the names of classes, functions, and variables should always be able to describe the role of the code reader in making it easy to know what it is. The simpler and more regular the form, the easier it is for people to perceive and understand. The use of ambiguous, obscure and non-standard nomenclature should be avoided.

4.4.1. Variables, objects, names of functions
Variables, objects, function names are all lowercase format, unless necessary, the words generally do not use the underscore "_" for segmentation;
The standard computer in English as the blueprint, to eliminate all pinyin, or phonetic English mixed naming;
Variable naming can only be used in the project in the English abbreviations available, such as the use of $data can not use the $data1, $data 2 so easily confusing form, should use $articledata, $userdata such a clear and easy to understand form;
can be reasonably abbreviated to the long name, such as $bio ($biography), $TPP ($threadsPerPage), provided that there is such an existing abbreviation in English, or the letter is in accordance with the English abbreviation specification;
Must be aware of the use of the word of speech in English words, in the scope of the relevant jurisdiction, most of the use of $enable***, $is * * *, the form of the former followed by verbs, the latter followed by adjectives.

4.4.2. constant
Constants should always be named with all uppercase letters, and in a few cases you can use dashes to separate the words.
PHP's built-in values TRUE, FALSE, and Null must all be written in uppercase letters.

4.5. Initialization of variables and logic checking
Any variable must be first made before it is cumulative, shown directly, or stored, for example:
$number = 0; Numeric type initialization
$string = '; String initialization
$array = Array (); Array initialization

To determine a variable that cannot be determined (not knowing whether it has been assigned), use empty () or isset () instead of using the form directly if ($switch) unless you know for sure that the variable has already been initialized and assigned a value.
The difference between empty () and Isset () is:
l bool Empty (mixed Var)
N if Var is non-empty or Non-zero, empty () returns FALSE. In other words, "", 0, "0", NULL, FALSE, Array (), Var $var; and objects that do not have any attributes will be considered empty and TRUE if Var is empty.
l BOOL Isset (mixed var[, mixed var[, ...)]
N returns TRUE if VAR exists, otherwise returns FALSE.
N If you have freed a variable with unset (), it will no longer be isset (). If you use Isset () to test a variable that is set to NULL, it returns FALSE. Also note that a null byte ("" ") is not equivalent to PHP's null constant.
To determine whether a variable is an array, use Is_array (), which is especially useful for an array of traversal operations, such as foreach (), because foreach () will complain about a variable of a non-array type without prior judgment;
To determine whether an array element exists, you can use Isset ($array [' key ']), or use empty (), the similarities and differences are seen.

4.6. Safety
Variables in PHP do not have to be stated in advance as C does, and the interpreter will automatically create them the first time they are used, and the same type does not need to be specified, and the interpreter is determined automatically according to the context environment. From a developer's point of view, this is an extremely convenient approach. A variable is created and can be used anywhere in the program. The result is that developers often don't pay attention to initializing variables. Therefore, in order to improve the security of the program, we cannot trust any variables that are not explicitly defined. The variables that are used in the program are overridden by a variable that is first made before the definition is used to prevent malicious constructs from being committed.
Details can be read ( This document, which lists the common PHP security issues, it is necessary to read this document!

4.7. Compatibility
Code design should take into account the PHP high and low version of the characteristics of the current, should still be PHP 4.3.0 as the lowest through the platform, as far as possible not to use the newer PHP new functions, constants or constants. If you use a function that is only available in a higher version, you must encapsulate it two times, automatically determine the current PHP version, and write the compatible code in the lower version.
For individual functions, parameter requirements or code requirements should be based on a more rigorous version of PHP;
Do not use functions in the PHP extension module unless necessary. When used, the necessary judgment should be added and the necessary processing should be done when the server environment does not support this function. The description of the features in the documentation and in the program should also be added.

4.8. Code Reuse
Effective reuse of code can reduce the loss of efficiency and waste of resources. In the development of software projects in order to avoid duplication of work and waste of time. Developers should try to increase the reuse rate of existing code and devote more effort to the application of new technology and the development of innovative features.
L do not skimp on defining functions or classes when you need to use code more than once, and there are no built-in PHP functions available for the tasks you want to implement. The developer is required to place the function in the Include directory with the. func.php as the function file suffix, and to place the class in the Include/class directory, based on the function and invocation. More than 3 lines, to achieve the same function of the program should not be repeated in different programs, which is intolerable and evasive problem;
L do not at any time appear to have two or more similar code or code in the same program, even in different procedures, should try to avoid. Developers should always be able to find a way to avoid large sections of code (more than 10 lines) repeating or similar.
It is to be emphasized that although this section is short, but it is very need of experience, and will spend a lot of time and energy developers to optimize the part, any product developers must always be clear and understand the importance and necessity of code reuse, effectively enhance product efficiency, logic and readability, This is an excellent software developers must have the basic quality.

4.9. Other detail issues

4.9.1. Include Call
Contains the calling program file, use require_once all to avoid possible duplicate inclusion issues;
Contains the call cache file, use include_once or include because the cached file does not guarantee 100% to open correctly. When necessary, you can use @include_once or @include to ignore error prompts;
Include and invoke code with Phpcms_root. ' /' Start, avoid writing the program file name directly (for example: require_once ' x.php ';) practices;
All included and invoked program files, including but not limited to programs, caches, or templates, usually cannot be requested by a direct URL. PHPCMS determines whether a program is legitimately invoked by defining a markup constant in_phpcms in./include/ Therefore, in any of the included and invoked program files other than./include/, you need to include the following to make it impossible for visitors to request the file directly through the URL:
Defined (' In_phpcms ') or exit (' Access Denied ');

4.9.2. Error Reporting level
In the software development and commissioning phase, use Error_reporting (E_all) as the default error reporting level, which is the most rigorous, able to report all errors, warnings, and prompts in the program to help developers check and check the code to avoid most of the security and logic errors, Spelling errors. Error_reporting () can be set in the first few lines of./include/
When software is released, use Error_reporting (E_error e_warning e_parse) as the default error reporting level to benefit the user and minimize unnecessary error messages.
5. Database design
5.1. Field
5.1.1. table and field naming
The names of tables and fields are based on the conventions of the previous 4.4 naming principles.
All data table names, as long as the name is a numbered word, you must name it in a complex number, such as phpcms_member (user table), a field that stores multiple items, or a field that represents a quantity, and should also be named in the plural, for example: hits (view count), items (content quantity).
When a field is connected between several tables, be aware of the unity of the associated field names between the table and the table, such as the ArticleID in the Phpcms_article_1 table and the ArticleID in the Phpcms_article_data_1 table.
A field that represents an ID from increment, usually in the following forms:
L in general, use the form of full name, such as UserID, ArticleID;
L do not have a functional role, only for the convenience of management and maintenance of the ID, you can use the form of full name, you can only name it as an ID.
Space is limited, not to repeat, but all the table, field-related naming, make sure that a large number of references to phpcms existing fields, to ensure the naming system and uniformity.
5.1.2. Field structure
A field that allows null values, which, when compared, determine whether the database is null or not, and the value is not NULL. Therefore, based on efficiency considerations, all fields cannot be empty, that is, all not null;
Non-negative fields are not expected to be stored, such as each ID, number of postings, and so on, and must be set to the unsigned type. The unsigned type is one-fold larger than the range of positive integers that can be stored by a unsigned type, thus obtaining a larger numerical storage space;
A field that stores switches, option data, usually using tinyint (1)-Unsigned types, and a few situations may also use the method of an enum () result set. tinyint as a switch field, usually 1 is open, 0 is off, 1 is special data, such as N/A (not available), above 1 is a special result or switch binary number combination (see the relevant code in PHPCMS);
In a memory/heap type of table, pay particular attention to planning to conserve storage space, which saves more memory. For example, in the Cdb_sessions table, the storage of the IP address is split into 4 tinyint (3) unsigned type fields without the use of char (15);
Any type of data table, field space should be in line with sufficient, not wasteful principle, numeric type of field value range see the following table:
field type storage space (b) UNSIGNED value range
Tinyint 1 No -128~127
It's 0~255.
SmallInt 2 No -32768~32767
It's 0~65535.
Mediumint 3 No -8388608~8388607
It's 0~16777215.
int 4 No -2147483648~2147483647
It's 0~4294967295.
bigint 8 No-9223372036854775808
is 0

5.2.SQL statement
In all SQL statements, in addition to table name, field name, all statements and functions should be capitalized, should eliminate lowercase or mixed case. For example, the SELECT * from Phpcms_member is a code that does not conform to the specification.
A long SQL statement should have a proper line break, defined by keywords such as join, from, and order by.
In general, when you operate on multiple tables, you specify a 1~2 abbreviation for each table based on different table names to make the statement concise and readable.
Example of the following statement, is consistent with the specification:
$result = $db->query ("Select m.*, i.*
From ". Table_member. "M,". Table_memberinfo. "I
WHERE M.userid=i.userid and m.userid= ' $_userid ');

5.3. Performance and efficiency
5.3.1. Fixed length and variable length table
A data table containing any varchar, text, and other variable-length fields, which is a variable-length table, whereas a fixed-length table.
L for variable-length tables, many deletions and changes on them will cause more fragmentation in the table because of the different size of the record. You need to run optimize table regularly to maintain performance. and the fixed-length table does not have this problem;
L If there are variable-length fields in the table, converting them to fixed-length fields can improve performance because fixed-length records are easy to handle. However, before attempting to do so, the following questions should be considered:
l Use fixed-length columns to deal with some kind of compromise. They are faster, but occupy more space. Each value of a char (n) Type column always occupies n bytes (even if the empty string does), because when stored in a table, the length of the value is not sufficient to fill the right space;
L and varchar (n)-type columns take up less space because they are allocated only the space needed to store each value, and each value plus one byte is used to record its length. Therefore, if you choose between char and varchar type, you need to compromise time and space;
L variable-length tables to fixed-length tables, you cannot convert only one variable-length field, you must convert all of them. Also, you must use an ALTER TABLE statement to convert all at once, otherwise the conversion will not work;
L Sometimes can't use a fixed-length type, even if I want to. For example, for strings longer than 255 characters, there is no fixed-length type;
l When designing a table structure, if we can use fixed-length data type as long as possible, because the fixed-length table query, retrieve, update speed is very fast. Some key and frequently accessed tables can be split if necessary, such as a table with fixed-length data, and a table with no fixed-length data. For example, Phpcms's Phpcms_member table and so on. Therefore, the planning data structure needs to be considered in a global situation;
When the table structure is designed, it should be done just right and hashed to realize the optimal data storage system.
5.3.2. Operation and Retrieval
Numeric operations are generally faster than string operations. For example, comparison operations can be compared by logarithm in a single operation. The string operation involves a few byte-per comparisons, and if the string is longer, the comparison is more.
If the number of values in a string column is limited, the superiority of the numerical operation should be obtained by using the generic integer or Emum type.
Smaller field types are always much quicker to handle than larger field types. For strings, the processing time is directly related to the string length. In general, smaller table processing is faster. For a fixed-length table, you should select the smallest type, as long as you can store the desired range of values. For example, if Mediumint is sufficient, do not choose bigint. For variable-length types, you can still save space. The value of one text type records the length of the value in 2 bytes, while a Longtext records the length of its value in 4 bytes. If the stored value is never longer than 64KB, using text will save each value by 2 bytes.
5.3.3. Structural Optimization and index optimization
Indexing accelerates query speed, while index optimization and query optimization complement each other by optimizing indexes based on queries or by optimizing queries based on existing indexes, depending on how the query or index is modified, and which has the least impact on the existing product architecture and efficiency.
Index optimization and query optimization are the crystallization of years of experience, but we can not elaborate on this, but still give a few basic principles.
First, find out which SQL statements are most commonly executed, based on the actual running and access of the product. The most commonly executed and most often present in a program is a completely different concept. The most frequently executed SQL statement can be divided into large tables (many data entries) and operations on small tables (less data entries). Whether a large table or a small table, there can be divided into read (SELECT) more, write (Update/insert) more or read and write operations.
For SQL statements that are often executed, you need to pay particular attention to large table operations:
L Write a lot of, usually can use write caching method, first need to write or need to update data cache to file or other table, regularly to large table for bulk write operation. At the same time, we should try to make the large table which is often read and written as a fixed-length type, even if the original structure of the large table is not fixed length. Large table length, can change the data storage structure and data reading mode, a large table to be broken into a read and write more fixed-length table, and a read more write less variable long table to achieve;
L Read more, you need to set the SQL query frequency for high-frequency SQL statements of the index and Federated Index.
The small table is relatively simple, adding a specific index that meets the requirements of the query, usually the effect is more obvious. At the same time, the fixed-length small table also benefits the efficiency and the load ability enhancement. Small fixed-length tables with fewer fields can even be indexed.
Second, look at the conditions of the SQL statement and the sort field is very dynamic (that is, according to the different function switches or attributes, SQL query conditions and the change of the sort field is very large), the dynamic of the SQL statement is too high to be optimized through the index. The only way to do this is to cache the data, update it regularly, and apply it to situations where the results are not demanding.
MySQL index, commonly used with primary KEY, index, unique several, please refer to the MySQL documentation. Typically, the PRIMARY key and the unique index are faster than index when a single table data value is not duplicated, please use it as appropriate.
In fact, the index is the conditional query, sorting the read operation resource consumption, distributed to the write operation, the more indexes, the more disk space consumption, the more slow write operation. Therefore, the index must not be blindly added. The most fundamental starting point for the field index is still the probability of executing the SQL statement, the size of the table, and the frequency of the write operation.
5.3.4. Query optimization
MySQL does not provide optimization features for query conditions, so developers need to optimize the order of the query in the program. For example, the following SQL statement:
SELECT * FROM table WHERE a> ' 0 ' and b< ' 1 ' ORDER by C LIMIT 10;

In fact, regardless of the a> ' 0 ' or b< ' 1 ', the result is the same, but the query speed is very different, especially when you are working on a large table.
developers need to keep this principle in mind: the first conditions must be the conditions for filtering and excluding more results; second, and so forth. Therefore, the distribution of the values of the different fields in the table has a great effect on the query speed. The conditions in the order by are related only to the index, regardless of the conditional sequence.
In addition to conditional order optimization, for fixed or relatively fixed SQL query statements, you can also optimize the index structure to achieve a fairly high query speed. The principle is that, in most cases, a federated index, based on the order of the Where condition and the order of the sorted field of the ordering by, is the optimal index structure that matches this SQL statement. Although, the fact of the product can not only consider a SQL statement, but also take into account the space footprint to establish too many indexes. The
also takes the SQL statement above as an example, the optimal speed of index optimization can be seen when the table record reaches millions or even tens.
According to the two principles of conditional optimization and index optimization above, the optimal conditional order scheme can be obtained when the value of table table is as follows:
Field a field B field C
1 7
2 8 ten
3 9
-1 0
Best Conditions:b< ' 1 ' and a> ' 0 '
Optimal index: Index ABC (b, A, c)
reason:b< ' 1 ' as the first condition can first filter out 75% of the results. If you use a> ' 0 ' as the first condition, you can only filter out 25% results
Note 1: field C because it does not appear in the condition, the conditional order optimization is irrelevant
Note 2: The optimal index is derived from the optimal conditional order, not the SQL statement in the example.
Note 3: The index is not a physical order to modify the data store, but rather a virtual pointer that is implemented by the physical data corresponding to a specific offset


Explain statement is an easy way to detect whether indexes and queries can match well. Run explain+ query statements in phpMyAdmin or other MySQL clients, such as explain select * FROM table WHERE a> ' 0 ' and b< ' 1 ' order by C; This form, even if the developer does not have to die Millions data, you can also verify that the index is reasonable, relevant details please refer to the MySQL description.
It is worth noting that the Using Filesort is the least desirable case, and if explain the result, the database specifically creates a temporary table file for the query to cache the results and deletes it after the query has ended. As we all know, hard disk I/O speed is always the bottleneck of computer storage, therefore, the query should do its utmost to avoid the high execution frequency of SQL statements using Filesort. Although it is never possible for a developer to guarantee that all SQL statements in a product will not use Filesort.
Limited to space, this document is far from covering all aspects of database optimization, such as the reusability of federated indexes and common indexes, the index design of join joins, memory/heap tables, and so on. Database optimization is in fact a lot of factors and pros and cons of constantly weighing, modifying, only in the success and failure experience hashed can be drawn from the experience, this experience is often the most valuable and valuable.
5.3.5. Compatibility issues
Due to the large changes in MySQL 3.23 to 5.0, the program tries not to use special SQL statements to avoid compatibility problems and makes database porting difficult.
typically in MySQL version 4.1, phpcms should be stored using a comparable character set, such as Gbk/big5/utf-8. Although the traditional latin1 coding has some compatibility, it is still not the recommended choice. When using the corresponding Non-default character set, the program needs to use set NAMES ' Character_set ' each time it is run to specify the character set of the connection, transmission, and result.
Mysql more than 5.0 new Sql_mode, the default Sql_mode depending on the server installation settings, so the program every time you need to use Set sql_mode= '; To specify the current SQL mode.
6. Template Design
6.1. Code tags
HTML code tags are all lowercase letters, eliminate any way to use uppercase letters

All logical bodies in the template, such as {if}, {loop}, and so on, must use HTML annotations (<!---->) before and after, which is similar to the <!--{if expr}--> form. In fact, the phpcms template compiler supports a logical body without HTML annotations, but adding annotations can make the template more readable, while making it easier for users to modify the template using Dreamweaver or FrontPage.
6.2. Rules of writing
6.2.1. HTML
All HTML tag parameter assignments need to be enclosed in double quotes, for example, you should use the

<input type= "text" name= "test" value= "OK" >
and absolutely no use

<input Type=text name=test value=ok>

In any case, the template files in the product must be written in the form of handwritten HTML code, and can never be written or modified using automatic Web authoring tools such as Dreamweaver, FrontPage, and so on.
6.2.2. Variable
The variables used in the template are divided into several ways, depending on the role and location of the occurrence:
In the logical body, the enclosed part, such as this form, in which the variable writing specification is exactly the same as the PHP program;
Developers need to use {} to enclose variables in order to avoid template compilation errors, possibly as follows:
L variables containing brackets or other sensitive characters (including but not limited to "$", "'", etc.) are correctly written to descriptionnew[{$buddy [Buddyid]}];
L The subscript of the array is variable, the correct writing is {$extcredits [$creditstrans][title]};
L Other variables are very complex situations.
6.2.3. Language elements
6.2.4. Indentation
In Phpcms's *.html template file, because of its logical structure, the indentation of any HTML itself is not considered, and all indentation is meant to be a logical indentation structure. Indent tab, do not use a space as the indent symbol, only the appropriate break-through. For example:

<!--{Loop $articles $article}-->
<table cellspacing= "0" cellspadding= "0" border= "0" >
<tr><td>{$article [' title ']}</tr></td>
7. Files and directories
7.1. File naming
All program or half program files that contain PHP code should be extended in lowercase. php instead of. phtml,. PhP3,. Inc,. class, etc. as extensions.
General Procedures
Programs that can be called directly by a URL, such as list.php, index.php, are named directly using the program name +.php
function libraries and class library programs
Use lowercase. func.php and. class.php as the extension respectively. function libraries and class library programs can only be referenced by other programs, not run independently. It cannot contain any process code that is not part of any function or class.
Process procedures
Use lowercase. inc.php as the extension. Can only be referenced by other programs, not run independently. It cannot contain program code for any function or class code.
Template source Files
In lowercase. html as the extension. Template source files are written according to the Phpcms template encoding rules and are not executable programs and can only be resolved by the phpcms template compiler and placed under other template directories under./templates/default or./templates.
Template destination File
The template file is compiled automatically after the target program is generated, in lowercase. PHP as an extension, stored in the./data/templates directory.
Language Pack File
With lowercase. lang.php as the extension, only the language pack information used by the template or program is stored.
Caching files
This type of file is automatically generated by the system, named in Cache_xxx.php, usergroup_xxx.php, style_xxx.php and other similar forms, and is stored in the./data/cache directory.
7.2. Directory naming
The Phpcms directory naming is based on the conventions of the previous 4.4 naming principles. In the case of possible, more in the plural form, such as./templates,/images, etc.
Because of the small number of directories, so the directory naming is mostly a habit and convention, developers need to create a new directory, should be consulted with the project team members, agreed to implement.
7.3. Empty Directory Index
Please place a 1-byte index.htm file in all directories that do not contain ordinary programs (that is, programs that can be called directly by the URL), with a single space. Virtually all directories are of this type except the Phpcms root directory, so developers need to place all of these directories in empty index.htm files to avoid server files being indexed and listed when the directory listing of the HTTP server is open.
Attachment directory, such as sensitive directories, to implement the function in the program, when the new subordinate directory, you must automatically write an empty index.htm file, to avoid the new directory is indexed problems.

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