PHP coding specifications are displayed in the PHPCMS development documentation.

Source: Internet
Author: User
This shows the encoding specification from the PHPCMS development documentation. although it is called the PHPCMS development specification, I think this applies to all PHP programming. After writing so many PHP codes, many codes may not be able to compare and correct the codes in the future. Note: This shows the encoding specification from the PHPCMS development documentation. although it is called the PHPCMS development specification, I think this is the case for all PHP programming. After writing so many PHP codes, many codes may not be able to compare and correct the codes in the future.

Phpcms Coding Specification
1. introduction .... 2
2. applicability .... 2
3. importance and benefits of standardization .... 3
4. PHP coding specifications and principles .... 3
4.1. Code mark... 3
4.2. comment... 3
4.3. writing rules... 4
4.3.1. indent... 4
4.3.2. braces {}, if, and switch. 4
4.3.3. operators, parentheses, spaces, keywords and functions... 5
4.3.4. function definition... 6
4.3.5. quotation marks... 6
4.3.6. multi-language problems... 7
4.4. naming principles... 8
4.4.1. variable, object, function name... 8
4.4.2. constant... 8
4.5. Variable initialization and logic check... 8
4.6. security... 9
4.7. compatibility... 9
4.8. code reuse... 10
4.9. Other details... 10
4.9.1. include call... 10
4.9.2. Error Report level... 11
5. database design .... 11
5.1. field... 11
5.1.1. table and field naming... 11
5.1.2. field structure... 11
5.2. SQL statements... 12
5.3. performance and efficiency... 13
5.3.1. fixed length and variable length table... 13
5.3.2. calculation and retrieval... 13
5.3.3. structure optimization and index optimization... 14
5.3.4. query optimization... 14
5.3.5. compatibility issues... 16
6. Template design .... 16
6.1. Code mark... 16
6.2. writing rules... 16
6.2.1. HTML. 16
6.2.2. variables... 16
6.2.3. language elements... 17
6.2.4. indent... 17
7. files and directories .... 17
7.1. file name... 17
7.2. directory name... 18
7.3. empty directory index... 18

1. Introduction
This specification is composed of programming principles. It integrates and refines the mature experience accumulated by developers for a long time and is intended to help build a consistent programming style. This document will be updated occasionally if necessary to get twice the result with half the effort.
Copyright: Shaanxi luolu Network Technology Co., Ltd. All rights reserved
Last Updated: November 20-2006

2. applicability
Unless otherwise stated, the following rules are applicable to phpcms projects and most of them are applicable to other PHP projects in the company.

3. importance and benefits of standardization
When a software project tries to comply with public consistency standards, it makes it easier for the developer involved in the project to understand the code in the project and understand the program status. This allows new participants to quickly adapt to the environment and prevents some participants from creating a set of styles and forming a habit for life out of time-saving needs, this results in other people wasting too much time and energy reading. In a consistent environment, encoding errors can also be reduced. The defect is that each person's standards are different, so it takes some time to adapt to and change their encoding style, temporarily reducing work efficiency. It is worthwhile to consider the temporary reduction of work efficiency from the long-term healthy development of the project and the higher team efficiency in the future. it is also a necessary process. Standards are not the key to a successful project, but they can help us achieve higher efficiency in our team collaboration and accomplish our tasks more smoothly.
1. programmers can understand any code and find out the program status.
2. newcomers can quickly adapt to the environment
3. prevent new PHP contacts from creating a new style and forming a habit for life out of time-saving needs.
4. prevent new PHP contacts from making the same mistake again and again
5. in a consistent environment, people can reduce the chance of making mistakes.
6. programmers have the same enemy

4. PHP coding specifications and principles

4. 1. Code mark
PHP programs can use or define PHP code. this form can be used when pure variables are embedded in HTML pages.
In recent years, the PHP development team has been advocating code standardization and standardization. PHP may not be recommended or even canceled in future versions. therefore, to enhance program compatibility, we will unify

4. 2. Notes
Annotations are used to add brief introductions to codes that are easy to forget. Use the C-style comments "/**/" and standard C ++ comments "//".

Some temporary code and debugging code are inevitably left in program development. such code must be annotated to avoid future forgetting. For all temporary, debugging, and experimental code, you must add a unified annotation mark "// debug" followed by the complete annotation information, this allows you to check whether there are any problematic code in the program in batches before the program release and final debugging. For example:
$ Num = 1;
$ Flag = TRUE; // debug is not sure whether to assign a value to $ flag.
If (empty ($ flag )){
// Statements
}

4. writing rules

4.3.1. indent
The unit convention for each indent is a TAB (8 blank characters in width). each developer involved in the project needs to set it forcibly in the editor (UltraEdit, EditPlus, Zend Studio, etc, in case that the code is forgotten, the format is not standardized.
This indent specification applies to functions, classes, logical structures, loops, and so on in PHP and JavaScript.

4.3.2. braces {}, if, and switch
The beginning bracket is the same as the keyword, and the end bracket is the same as the keyword;
In the if structure, if and elseif are in the same direction as the two parentheses, each with a space on the left and right, and all braces start with a separate line. In addition, even if there is only one line after the if statement, braces must be added to ensure the structure is clear;
In the switch structure, after a case block is processed, the skipped case block is processed. Therefore, break needs to be added in most cases. The position of break depends on the program logic. it can be the same line as case or a new line. However, in the same switch body, the position format of break should be consistent.
The following are examples that comply with the above specifications:
If ($ condition)
{
Switch ($ var)
{
Case 1: echo 'Var is 1'; break;
Case 2: echo 'Var is 2'; break;
Default: echo 'Var is neither 1 or 2'; break;
}
}
Else
{
Switch ($ str)
{
Case 'ABC ':
$ Result = 'abc ';
Break;
Default:
$ Result = 'unknown ';
Break;
}
}

4.3.3. operators, parentheses, spaces, keywords, and functions
Each operator must have a space in the middle of the value or expression involved in the operation on both sides. the only special case is that no space is added on both sides of the character concatenation operator number;
The left parenthesis "(" should be closely related to the function keyword. In addition, space should be used to separate "(" from the preceding content;
Except for ")" or ".", brackets ")" are separated by spaces;
Except for the special needs of strings, generally, there are no consecutive spaces in the program and HTML;
Under no conditions can blank lines with tabs or spaces appear in the PHP program. that is, such blank lines should not contain any tabs or spaces. At the same time, no additional TAB or space is allowed at the end of any program line. Most editors have the function of automatically removing spaces at the end of a line. if you are not familiar with it, you can use it temporarily to avoid unnecessary spaces;
The upper and lower parts of a large program must be added with blank lines. Only one blank line is used between two program blocks, and multiple lines are prohibited.
The block Division should be as reasonable as possible. too large or too small splitting will affect others' reading and understanding of the code. Generally, it can be divided by large function definitions, logical structures, and functional structures. Blocks with less than 15 lines can be left blank;
In the description or display section, if the content contains Chinese characters, numbers, and English words, spaces should be added before and after the numbers or English words.

Based on the above principles, the following examples describe the correct writing format:
$ Result = ($ a + 1) x 3/2 + $ num). 'test ';
$ Condition? Func1 ($ var): func2 ($ var );
$ Condition? $ Long_statement
: $ Another_long_statement;
If ($ flag)
{

// Statements
// More than 15 lines
}
Showmessage ('use restore. php to restore data. ');

4.3.4. function definition
L The name of the parameter is consistent with that of the variable;
L left parentheses in the function definition, which are close to the function name without spaces in the middle;
L start with another line in the left braces;
L parameters with default values should be placed behind the parameter list;
L a space is added between parameters during function call and definition;
L check carefully and avoid the difference between the start and end indent positions of the function.

For example, compliant with the standard definition:
Function authcode ($ string, $ operation, $ key = '')
{
If ($ flag)
{
// Statement
}
// Function body
}

Non-compliant definition:
Function authcode ($ string, $ operation, $ key = ''){
// Function body
}

4.3.5. quotation marks
In PHP, single quotes and double quotes have different meanings. The biggest differences are as follows:
In single quotes, any variable ($ var) or special escape characters (such as "\ t \ r \ n") will not be parsed, so PHP is faster to parse, only escape characters such as "\" and "\" can escape single quotes and backslash themselves;
In double quotation marks, the variable ($ var) value is substituted into the string, and special escape characters are also parsed into a specific single character. There are also some special functional escaping for the above two features, for example, "\ $" and "{$ array ['key']}. In this way, although programming is more convenient, PHP parsing is also slow;
In the array, if the subscript is not an integer but a string type, you must enclose the subscript in single quotes. the correct syntax is $ array ['key'], instead of $ array [key]. because the incorrect writing method will make the PHP parser think that the key is a constant, and then first judge whether the constant exists. if it does not exist, the "key" is used as the subscript into the expression, and the error event is triggered, generate a Notice-level error.
Therefore, double quotation marks are not allowed in most cases where single quotes can be used. Based on the above analysis, single quotation marks can or must be used, including but not limited to the following:
L The string is a fixed value and does not contain special escape characters such as "\ t;
L fixed subscript of the array, for example, $ array ['key'];
L The expression does not need to include variables, such as $ string = 'test';, rather than $ string = "test $ var ";
With the exception, in regular expressions (for preg _ series functions and ereg series functions), all phpcms uses double quotation marks, which is convenient for manual analysis and writing and keeps the regular expressions uniform, reduce unnecessary analysis obfuscation.
In Database SQL statements, all data cannot be enclosed in single quotes, but must be processed by the intval function before SQL query. all strings must be enclosed in single quotes, to avoid possible injection vulnerabilities and SQL errors. The correct syntax is as follows:
$ Catid = intval ($ catid );
SELECT * FROM phpcms_member WHERE username = '$ _ username' AND catid = $ catid;

Addslashes () must be processed before all data is inserted into the database to avoid errors when inserting the database without escaping special characters. If the file common has been introduced in phpcms. inc. php, then all the variables obtained through GET, POST, and FILE are escaped by default using addslashes () and do not need to be repeated. If data processing is necessary (for example, for direct display), you can use stripslashes () for restoration, but the data must be escaped again before being inserted into the database.
In cached files, the value of cached data is typically escaped using addcslashes ($ string.

4.3.6.

4. naming principles
Naming is the core of program planning. The ancients believed that as long as they knew the real name of a person, they would gain incredible power over that person. As long as you give things a correct name, it will give you and people later more powerful than the code.
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.
In general conventions, the names of classes, functions, and variables should always be able to describe the role of the code so that the code reader can easily understand it. The simpler the form, the more rules there are, the easier it is to perceive and understand. Avoid ambiguous and unstandard naming.

4.4.1. variable, object, function name
All variables, objects, and function names are in lowercase. unless necessary, words are not separated by underscores;
Use standard computer English as the blueprint to eliminate all naming methods that mix pinyin and pinyin English;
Variable naming can only be an abbreviated term that can be traced in a project. for example, you can use $ data instead of $ data1 or $ data2, which is prone to confusion, $ articledata and $ userdata should be clearly understood;
A reasonable abbreviation for long names, such as $ bio ($ biography) and $ tpp ($ threadsPerPage), is provided that such an abbreviated form exists in English, or letters must comply with the English abbreviation specification;
You must be clear about the part of speech of the English words used. most of the permissions are in the form of $ enable *** and $ is ***. The former is followed by a verb, the latter is followed by an adjective.

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

. Variable initialization and logic check
Any variable must be first-made before it is accumulated, directly displayed, or stored. for example:
$ Number = 0; // numeric initialization
$ String = ''; // string initialization
$ Array = array (); // array initialization

You can use empty () or isset () instead of using if ($ switch) to determine a variable that is uncertain (not sure whether it has been assigned a value, unless you know exactly that the variable has been initialized and assigned a value.
The difference between empty () and isset () is:
L bool empty (mixed var)
N If var is a non-null or non-zero value, empty () returns FALSE. In other words, "", 0, "0", NULL, FALSE, array (), var $ var; and objects without any attributes will be considered empty, if var is null, TRUE is returned.
L bool isset (mixed var [, mixed var [,...])
N Returns TRUE if var exists; otherwise, FALSE.
N If unset () has been used to release a variable, it will no longer be isset (). If you use isset () to test a variable that is set to NULL, FALSE is returned. Note that a NULL byte ("\ 0") is not equivalent to the NULL constant of PHP.
To determine whether a variable is an array, use is_array (). This kind of judgment is especially suitable for traversing the array, such as foreach (), because if no prior judgment is made, foreach () an error is reported for non-array variables;
To determine whether an array element exists, you can use isset ($ array ['key']) or empty.

4. 6. security
Variables in PHP do not need to be declared in advance as they are in the C language. the interpreter will automatically create them when they are used for the first time. the interpreter will automatically determine the variables based on the context environment. From the developer's point of view, this is undoubtedly an extremely convenient solution. Once a variable is created, it can be used anywhere in the program. The result is that developers often do not pay attention to initialization variables. Therefore, to improve program security, we cannot trust any variables that are not clearly defined. All variables should be first made before they are defined and used to prevent malicious construction of submitted variables from overwriting the variables used in the program.
For details, see (http://www.securereality.com.au/studyinscarlet.txt) this document, which lists common PHP security issues, reading this document is very necessary!

4. 7. compatibility
The code design should take into account the features of PHP high and low versions. Currently, PHP 4.3.0 should be used as the lowest passing platform, and functions, constants, or constants added by PHP in higher versions should be avoided as far as possible. If you use a function that is only available in a later version, you must perform secondary encapsulation on the function, automatically determine the current PHP version, and compile the compatible code in a lower version;
For some functions, the parameter requirements or code requirements should be subject to the stricter PHP version;
Do not use functions in the PHP extension module unless necessary. Make necessary judgments when using the function. when the server environment does not support this function, perform necessary processing. Compatibility instructions should also be added to the functional instructions in documents and programs.

4. 8. code reuse
Effective Code reuse can reduce the loss of efficiency and waste of resources. When developing software projects, to avoid repetitive work and a waste of time. Developers should try their best to improve the reuse rate of existing code and devote more energy to the application of new technologies and innovative development of new functions.
L when you need to use code multiple times and there is no built-in PHP function available for the task you want to implement, do not mean defining a function or class. The developer must place the function in the include directory and use. func. php as the extension of the function file according to the function and call conditions, and place the class in the include/class directory. If there are more than three lines, the program implementing the same function should not appear in different programs multiple times. this is an issue that cannot be tolerated or avoided;
L do not show two or more similar code or the same code in the same program at any time, even in different programs, you should try your best to avoid it. Developers should always be able to find situations where code segments (more than 10 lines) are repeated or similar.
It should be emphasized that although this part is short in length, it is a part that requires much experience and will spend a lot of time and energy on optimization by developers, any product developer must understand the importance and necessity of code reuse at all times, and work hard to improve product efficiency, logic, and readability. this is a basic quality that a good software developer must possess.

4. 9. Other Details

4.9.1. include call
Include the calling program file. use require_once to avoid possible repeated inclusion issues;
Including calling the cache file. because the cache file cannot be properly opened by 100%, use include_once or include. If necessary, you can use the @ include_once or @ include method to ignore the error message;
The inclusion and call code must start with PHPCMS_ROOT. '/'. do not directly write the program file name (for example, require_once 'X. php;
All included and called program files, including but not limited to programs, caches, or templates, cannot be directly requested by URLs. Phpcms defines a Mark constant IN_PHPCMS in./include/common. inc. php to determine whether the program is legally called. Therefore, in addition. /include/common. inc. any program file other than php that is included and called must contain the following content, so that visitors cannot directly request the file through the URL:
Defined ('in _ PHPCMS ') or exit ('Access Denied ');

4.9.2. Error Report level
In the software development and debugging phase, use error_reporting (E_ALL); as the default error reporting level, which is the strictest and can report all errors, warnings, and prompts in the program, to help developers check and verify code and avoid most security and logic errors and spelling errors. Error_reporting () can be set in the first few rows of./include/common. inc. php.
When the software is released, use error_reporting (E_ERROR | E_WARNING | E_PARSE) as the default error report level, so that you can use it and minimize unnecessary error messages.
5. database design
5. 1. Fields
5.1.1. table and field naming
Before naming tables and fields, the 4.4 naming principles Convention serves as the basic principle.
All data table names, as long as their names are only a handful of nouns, must be named in the form of a plural, for example, phpcms_member (user table); a field that stores multiple pieces of content, or a field that represents a number, it should also be named in the plural form, for example, hits (viewing times) and items (content quantity ).
When Fields in several tables are related to the connection, pay attention to the unified names of the associated fields between the tables, such as the articleid and the articleid in the phpcms_article_data_1 table in phpcms_article_data_1.
Fields that represent id self-increment are usually in the following forms:
L generally, full names are used, such as userid and articleid;
L It has no functional function. it only sets an id for convenient management and maintenance. it can be in the full name or named as id only.
The length limit cannot be described in detail. However, for all the names related to tables and fields, please refer to the existing phpcms field naming methods in large quantities to ensure the systematic and unified naming.
5.1.2. field structure
A field that allows NULL values. when the database performs a comparison operation, it first determines whether it is NULL. if it is not NULL, the database performs a value pair. Therefore, based on efficiency, all fields cannot be blank, that is, all not null;
It is not expected to store non-negative fields, such as the id and number of senders, which must be set to the UNSIGNED type. The UNSIGNED type is twice the range of positive integers that can be stored by non-UNSIGNED types. Therefore, a larger numerical storage space can be obtained;
Fields that store Switch and option data usually use the tinyint (1) Non-UNSIGNED type. in rare cases, the enum () result set method may be used. When tinyint is used as the switch field, usually 1 is open; 0 is closed;-1 is special data, such as N/A (unavailable ); if the value is greater than 1, it is a special result or a combination of switch binary numbers (see the relevant code in phpcms );
For MEMORY/HEAP tables, pay special attention to plan to save storage space, which will save more MEMORY. For example, in the cdb_sessions table, the IP address storage is split into four tinyint (3) UNSIGNED fields without using char (15;
For any type of data tables, the field space should be sufficient and free of waste. the value range of the field of the value type is shown in the following table:
Field type bucket (B) UNSIGNED value range
Tinyint 1 no-128 ~ 127
Is 0 ~ 255
Smallint 2 no-32768 ~ 32767
Is 0 ~ 65535
Mediumint 3 no-8388608 ~ 8388607
Is 0 ~ 16777215
Int 4 no-2147483648 ~ 2147483647
Is 0 ~ 4294967295
Bigint 8 no-9223372036854775808
~ 9223372036854775807
Is 0
~ 18446744073709551615

5.2. SQL statements
In all SQL statements, except the table name and field name, all statements and functions must be written in uppercase. For example, select * from phpcms_member is a non-compliant statement.
A long SQL statement should have an appropriate line break, which is defined based on keywords such as JOIN, FROM, and ORDER.
In general, when performing operations on multiple tables, you must specify a 1 ~ The abbreviation of two letters to facilitate concise and readable statements.
The following statement example is compliant with the specifications:
$ 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 that contains variable-length fields such as varchar and text is a variable-length table, and vice versa.
L for a variable-length table, because the record size is different, many deletions and changes on it will cause more fragments in the table. Optimize table needs to be run regularly to maintain performance. The fixed-length table does not have this problem;
L if the table contains variable-length fields, converting them into fixed-length fields can improve the performance, because fixed-length records are easy to process. However, before trying to do so, consider the following:
L using a fixed-length column involves some compromise. They are faster, but occupy more space. Each value of a char (n) Type column must take up to n bytes (even if it is an empty string), because when stored in the table, the length of the value is insufficient and spaces will be filled on the right;
L varchar (n) columns occupy less space, because only the space required to store each value is allocated to them, and each value plus one byte is used to record its length. Therefore, if you select the char and varchar types, you need to make a compromise between time and space;
L The conversion from a variable-length table to a fixed-length table cannot only convert one variable-length field. all of them must be converted. In addition, you must use an alter table statement to convert all data at the same time. Otherwise, the conversion will not take effect;
L sometimes the fixed length type cannot be used, even if you want to do so. For example, for a string longer than 255 characters, there is no fixed length type;
L when designing the table structure, if you can use the fixed-length data type, try to use the fixed-length data type, because the query, retrieval, and update speed of the fixed-length table is very fast. If necessary, you can split some key tables that are frequently accessed. for example, a table with fixed-length data and a table with non-fixed-length data. For example, the phpcms_member table of phpcms. Therefore, global consideration is required when planning the data structure;
During table structure design, the data storage system should be optimized and optimized.
5.3.2. operations and retrieval
Numeric operations are generally faster than string operations. For example, you can compare the logarithm of a single operation. The string operation involves several byte-by-byte comparisons. if the string is longer, there will be more such comparisons.
If the number of values in a string column is limited, the general integer or emum type should be used to obtain the superiority of numerical calculation.
Smaller field types are always much faster to process than larger field types. The processing time of a string is directly related to the length of the string. Generally, smaller tables process faster. For a fixed-length table, you should select the smallest type, as long as you can store the value of the required range. For example, if mediumint is enough, do not select bigint. The variable length type can still save space. A TEXT value records the length of a value in 2 bytes, while a LONGTEXT value records the length of a value in 4 bytes. If the length of the stored value never exceeds 64 kB, using TEXT will save each value 2 bytes.
5.3.3. structure optimization and index optimization
Indexes can accelerate the query speed, while index optimization and query optimization complement each other. indexes can be optimized based on queries or existing indexes, this depends on the query or index modification, which has the least impact on the existing product architecture and efficiency.
Index optimization and query optimization are the result of years of experience. we cannot elaborate on them here, but we still provide several basic principles.
First, find out which SQL statements are most commonly executed based on the actual operation and access status of the product. The concepts that are most often executed and most often present in programs are completely different. The most commonly executed SQL statements can be divided into large tables (with many data entries) and small tables (with few data entries. Large tables or small tables can be divided into multiple operations, including multiple SELECT operations, multiple write operations, or multiple read/write operations.
For SQL statements that are commonly executed, pay special attention to the following for large table operations:
L if there are many write operations, you can usually use the write cache method to first cache the data to be written or to be updated to a file or other tables, and regularly perform batch write operations on large tables. At the same time, we should try to make the large tables that are frequently read and written into a fixed-length type, even if the large tables in the original structure are not fixed-length. You can change the data storage structure and data reading mode to split a large table into a variable-length table with multiple reads and writes and a variable-length table with multiple reads and writes;
L if there are many read operations, you need to set indexes and joint indexes for high-frequency SQL statements based on the SQL query frequency.
Small tables are relatively simple. adding specific indexes that meet the query requirements usually results in obvious results. At the same time, the fixed length small table is also beneficial to the improvement of efficiency and load capacity. Small fixed-length tables with few fields, or even no index is required.
Secondly, check whether the SQL statement conditions and sorting fields are dynamic (that is, depending on the switch or attribute of different functions, the SQL query conditions and sorting fields vary greatly ), SQL statements that are too dynamic cannot be optimized through indexes. The only method is to cache the data and update it regularly, which is suitable for scenarios where the results do not have high requirements on effectiveness.
MySQL indexes are commonly used, including primary key, INDEX, and UNIQUE. For more information, see the MySQL documentation. In general, if the data values of a single table are not repeated, the primary key and UNIQUE indexes are faster than the INDEX. please use them as appropriate.
In fact, the index consumes read operation resources for conditional query and sorting and is distributed to write operations. the more indexes, the larger the disk space, and the slower the write operation. Therefore, you must not add indexes blindly. The most fundamental starting point for field indexing is the probability of SQL statement execution, table size, and frequent write operations.
5.3.4. query optimization
MySQL does not provide the optimization function for query conditions. Therefore, developers need to manually optimize the query conditions in sequence 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, no matter which condition a> '0' or B <'1' is in front of, the results are the same, but the query speed is quite different, especially when performing operations on large tables.
Developers need to keep this principle in mind: the first condition that appears must be the condition that filters out and removes more results; the second condition that appears, and so on. Therefore, the distribution of values of different fields in the table has a great impact on the query speed. The condition in order by is only related to the index and is irrelevant to the condition ORDER.
In addition to conditional order optimization, you can optimize the index structure for fixed or relatively fixed SQL query statements to achieve a high query speed. The principle is: in most cases, the joint index established based on the ORDER of the WHERE condition and the order by sorting field is the optimal index structure matching this SQL statement. Although, in fact, the product cannot only consider one SQL statement, but also cannot create too many indexes because of space occupation.
The preceding SQL statement is used as an example. when the number of records in the table reaches millions or even tens of millions, we can see that the speed of index optimization is improved.
Based on the two principles of the above condition optimization and index optimization, when the values of the table are as follows, the optimal condition sequence scheme can be obtained:
Field a field B field c
1 7 11
2 8 10
3 9 13
-1 0 12
Optimal condition: B <'1' AND a> '0'
Optimal INDEX: INDEX abc (B, a, c)
Cause: B <'1' can be used as the first piece to filter out the 75% results first. If a> '0' is used as the first piece, only 25% of the results can be filtered out first.
Note 1: field c does not appear in the condition, so the condition order optimization is irrelevant to it.
Note 2: The Optimal Index is obtained by the optimal condition sequence, not by the SQL statement in the example.
Note 3: The index is not used to modify the physical sequence of data storage, but a virtual pointer based on the physical data corresponding to a specific offset.

The EXPLAIN statement is a simple method to check whether the index and query can be well matched. Run the EXPLAIN + query statement in phpMyAdmin or other MySQL clients, for example, EXPLAIN select * FROM table WHERE a> '0' AND B <'1' ORDER BY c, even if developers do not need to simulate millions of data records, they can verify that the index is reasonable. For more information, see MySQL.
It is worth noting that Using filesort is the least suitable case. if this result is obtained by explaining, the database creates a temporary table file for this query to cache the results, and delete it after the query is complete. As we all know, hard disk I/O speed is always the bottleneck of computer storage. Therefore, you should do your best to avoid using filesort for SQL statements with high execution frequency. Even though, developers can never ensure that all SQL statements in the product do not use filesort.
This document does not cover all aspects of database optimization, such as the reusability of joint indexes and common indexes, the index design of JOIN connections, and MEMORY/HEAP tables. Database optimization is, in fact, constantly balancing and modifying between many factors and advantages and disadvantages. the experience can only be obtained through repeated scrutiny in the experience of success and failure. this experience is often the most valuable and valuable.
5.3.5. Compatibility issues
Since MySQL 3.23 to 5.0 changes a lot, do not use special SQL statements in the program as much as possible to avoid compatibility issues and cause difficulties for database transplantation.
Usually in MySQL 4.1 and later versions, phpcms should be stored using equivalent character sets, such as GBK/BIG5/UTF-8. Although the traditional latin1 encoding has certain compatibility, it is still not recommended. When a non-default character SET is used, set NAMES 'character _ set' must be used to specify the character sets for connection, transfer, and result each time the program runs.
Mysql 5.0 and later versions have several new SQL _modes. the default SQL _MODE varies depending on the server installation settings. Therefore, you must use SET SQL _MODE = ''for each running of the program to specify the current SQL mode.
6. Template design
6. 1. Code mark
All HTML code tags must be in lowercase letters. do not use uppercase letters.

All the logic bodies in the template, such as {if} and {loop}, must be annotated in HTML ( ), That is, similar . In fact, the phpcms template compiler supports writing logic bodies without HTML comments. However, adding annotations can make the template more readable and make it easier for you to modify the template using DreamWeaver or FrontPage.
6. 2. writing rules
6.2.1. HTML
All values of HTML tag parameters must be enclosed in double quotation marks. for example


But it cannot be used.


.
Under any circumstances, the template files in the product must be written in HTML code by hand, but they cannot be written or modified using automatic webpage creation tools such as DreamWeaver and FrontPage.
6.2.2. variables
The variables used in the template are divided into several methods based on different roles and locations:
L in the logic body, that is, the surrounded part, for example, in this form, the variable writing specification is completely consistent with that in the PHP program;
The developer needs to use {} to enclose the variables to avoid template compilation errors. the possible situations are as follows:
L variables that contain parentheses or other sensitive characters (including but not limited to "$" and ), the correct statement is descriptionnew [{$ buddy [buddyid]}];
L The subscript of the array is variable. the correct syntax is {$ extcredits [$ creditstrans] [title]}.
L other variables are very complex.
6.2.3. language element
6.2.4. indent
In the *. html template file of phpcms, due to its logical structure, indentation of HTML itself is not considered. all indentation means logical indent structure. The TAB mode is used for indentation. if spaces are not used as the indentation symbol, you only need to break the line properly. For example:




{$ Article ['title']}


7. files and directories
7. 1. file name
All program or semi-program files that contain PHP code should use lowercase. php as the extension, rather than. phtml,. php3,. inc,. class, and so on.
Common Program
Programs that can be directly called by URLs, such as list. php and index. php, are directly named using the program name +. php.
Function libraries and library-like programs
Use lower case. func. php and. class. php as extensions respectively. Function libraries and class libraries can only be referenced by other programs and cannot be run independently. It cannot contain any procedural program code that does not belong to any function or class.
Process procedure
Use lowercase. inc. php as the extension. It can only be referenced by other programs and cannot run independently. It cannot contain program code of any function or class code.
Template source file
Use a small write. html as the extension. The template source file is compiled according to the phpcms template encoding rules. it is not an executable program, but can only be parsed by the phpcms template compiler and placed in. /templates/default or. /other templates under templates.
Template target file
The target program automatically generated after the template file is compiled. it uses lowercase. php as the extension and is stored in the./data/templates directory.
Language Pack files
Use lowercase. lang. php as the extension and only store the language pack information used by the template or program.
Cached files
These files are automatically generated by the system and are named in the./data/cache directory in the form of cache_xxx.php, usergroup_xxx.php, and style_xxx.php.
7. 2. directory name
The conventions in "4.4 naming principles" before naming the phpcms directory are the basic principles. If possible, it may appear in the form of multiple numbers, such as./templates and./images.
Because the number of directories is small, the directory naming conventions are common. if developers need to create a new directory, they should negotiate with the project team members to reach an agreement before implementation.
7. 3. empty directory index
Please include a blank space in the contents of the index.htm file that can be directly used by urldirectly. To prevent the server files from being indexed and listed when the Directory Listing of the http server is opened.
The attachment directories and other sensitive directories must be implemented in the program. when a new directory is created, the system automatically writes an empty index.htm file to avoid indexing the new directory.

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.