Develop tutorial 1.2 using Drupal/PHP internally

Source: Internet
Author: User
Tags array definition doxygen drupal
In the internal development standard of DrupalPHP 1.2, the preface is often said: "There are no rules, not a square ". Good programming styles and specifications are important to developers and project management personnel. 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. Enable new participants to quickly adapt to the environment and prevent some participants from creating a set of styles and forming a habit of life for time saving. as a result, other internal development specifications using Drupal/PHP are 1.2
Preface
As a saying goes, "there are no rules, and it cannot be a square ". Good programming styles and specifications are important to developers and project management personnel.
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.

Chapter 2 Typographical Rules

1.1 indent
The code indent uses two spaces instead of the tab key, because the length Root displayed by the tab key is different when you view the code in different editors, although the space will increase the file size, these errors are insignificant.
In many editors, you can set the tab key to 2 spaces, if you are used to the tab key.

1.2 Space rules
Spaces should be used in the following cases:

1. there should be a space between the keyword and (for example:
While ($ user-> uid> 0 ){
?>
2. function names (there should be no space between them, for example:
Function arg (){
?>
3. there should be no space between the unary operator and its operand, unless the operand is a word, for example, typeof.
4. in the control section, in the for statement, ";" must be followed by a space.
5. each, followed by a space.

1.2.1. spaces must be added before and after logical operators, except for the plus or minus operation.
// Correct
$ A = $ B;
// Error
$ A = $ B;
$ A = $ B;
// Correct
$ A ++;
$ --;
// Error
$ A ++;
$ --;
?>



1.2.2 separate multiple parameters with spaces
// Correct
$ A, $ AB, $ c;
Arg ($ a, $ B, $ c );
// Error
$ A, $ AB, $ c;
Arg ($ a, $ B, $ c );
?>



1.2.3. spaces must be added after the syntax keyword.
Keywords such as if, for, while, and switch.
Example:
// Correct
For ($ a = 0; $ <10; $ a ++ );
// Error
For ($ a = 0; $ <10; $ a ++ );
?>



1.3 connection rules for strings and variables
The string is connected to the variable using ".", and there is a space around ".". when using "Auto Escape variable, you must add" {} "before and after the variable.
// Correct
$ Result = 'File _ '. $ var;
$ Result = 'File _ {var }';
// Error
$ Result = 'File _ '. $ var;
$ Result = 'File _ $ var ';
?>



1.4 one statement per line. unless these statements are closely related, only one statement is written in each line. Use blank lines to separate logical statements to improve program readability.
Correct
$ Node_types = node_get_types ('types', NULL, TRUE );

Foreach ($ node_types as $ type => $ info ){
//
}
?>


Error
$ Node_types = node_get_types ('types', NULL, TRUE );
Foreach ($ node_types as $ type => $ info ){
//
}
?>



1.5. Keywords
If, for, do, while, case, switch, default, and other statements occupy one row, and the execution statement of statements such as if, for, do, and while must contain complete brackets no matter how many statements {}
Example:
Correct
If (NULL = $ arg ){
Return;
}
?>


Error
If (NULL = $ arg) return;
?>



1.5.1, if
The format is as follows:
If (condition ){
//
}

If (condition ){
//
} Else {

}

If (condition ){
//
} Else {
//
}
?>



1.5.2,
The format is as follows:
For ($ I = 0; $ I <1; $ I ++ ){
//
}
?>



1.5.3, do
The format is as follows:
Unlike other compound statements, do statements always end.
Do {
//
} While (condition );
?>



1.5.4. do
The format is as follows:
Switch (expression ){
Case expression:
Statements;
Default:
Statements;
}
?>


Each set of statements (except default, should end with break, return, or throw. Do not let it be executed in sequence .)



1.5.5. try
The format is as follows:
Try {
Statements
} Catch (variable ){
Statements
}
?>



1.6 database

* The keywords in the query statement should be capitalized.

Chapter 2 naming rules
The naming rules of Linux C are consistent, including PHP, XHTML, CSS, and JS.
All the letters of the variable name are in lower case, and "_" is used as the boundary of each word ("-" is used in CSS, because many code generated by drupal uses "-" (such as block ID, it is usually similar to # block-vacation ).), The variable name must be meaningful to make the program clear at a glance.
In the project, variable names of the same meaning should be the same as possible. for example, $ node in the drupal Project indicates a node, which is used in many places. if the name is the same, you can see at a glance that this is a node. you can use the function operations of the node. to distinguish multiple nodes, you can add meaningful letters in front, for example, $ book_node and $ color_node.

2.1. constant
PHP constants should all use uppercase letters and use _ to correctly separate words.
Constants use the module name as the prefix to avoid conflicts between common words. For example, if your module is named test. module, the constant name should be like TEST_USER.
Define ('test _ CONFIRM_UID ', 0 );
?>



2.2 Global variables
Global variable naming rules: $ _ module name (Topic Name) _ global variable name
Example:
// Error
Globe $ records;
// Correct
Globe $ _ test_records;
?>



2.3 static variables
Static variables use the prefix s, for example:
$ S_records;
?>



2.4. temporary variables
Do not use temporary variables such as $ I and $ j that are frequently used in loops for other purposes.

2.5 function naming
The function name adopts the c gun convention. all letters use lowercase letters. The rule is: module name + _ + function name. Note that the name must not be the same as the related hook name of drupal.

2.6 file name naming
The file names should all be in lower case. The exception is document files, which are all capital and of the txt type.
For example:
LICENSE.txt
README.txt
INSTALL.txt

Chapter 2 programming specifications
The system uses the timestamp time () as the time Mark and writes data in the INT (10) type when storing data in mysql.
Single quotation marks are used. double quotation marks are used only when the quotation marks overlap. this saves hundreds of KB of memory for each process.
Unified use
?>, Disable ?>



3.1. array definition rules
Key and value must use single/double quotation marks.
// Correct
Array (
'Name' => 'myname ',
'Type' => 'mytype'
);
// Error
Array (
Name => myname,
Type => mytype
);
?>



3.2 do not use the default method to test variables/functions
// Correct
If ($ user> 0 ){
//
}

If (arg (1 )! = ''){
//
}
// Error
If ($ user ){
//
}

If (arg (1 )){
//
}
?>



3.3 file structure rules
The drupal module development rules are as follows (take the module name book as an example ):
Main module (book. module) contains hook_help (), hook_init (), hook_menu (), and some common functions of this module. for example, you need to call functions of other modules (except for core modules that must be enabled ), check whether the module is enabled (for example, module_exists ('book ');).
Book. admin. inc (code related to page management) and book. page. inc (code used for user operations) should be classified and placed. The "file" key in hook_menu should be used to point.
Some js plug-ins used in the module, such as jquery plug-ins, should be placed in the js folder in the module directory.

3.4 database operation rules

* Db_query_range () is used to query one or more records ().
* If you can add an ORDER for each query, sort it by INDEX.

3.5 annotations
The annotation document follows the Doxygen annotation style. the annotation block syntax is as follows (including css and js ):
/**
* Implementation of hook_cron ().
*/
Function node_cron (){
Db_query ('delete FROM {history} WHERE timestamp <% d', NODE_NEW_LIMIT );
}
?>


The comment block must be placed next to the function and there are no blank lines in the middle.
Drupal can understand the Doxygen constructor listed below. for details about the role of the constructor, see The Doxygen document:



* @ Mainpage
* @ File
* @ Defgroup
* @ Ingroup
* @ Addtogroup
* @ Param
* @ Return
* @ Link
* @ See
*@{
*@}

3.5.1, // $ id $
"// $ Id $" is used to track version numbers and the last modified users. it is placed at the forefront of each file in the form of annotations (including all files to be submitted to the version library, such as js and css ). When the code is submitted to CVS (SVN), the system will automatically parse and expand the label as follows:
// $ Id: node. module, v 1.947.2.29 2010/12/15 12:53:33 goba Exp $
?>



Chapter 2. writing secure code
4.1 process user input and output
The data on the forms (including some ajax) submitted by non-drupal hook_form should be filtered for security. The following lists some filter functions provided by drupal.

* Check_plain (HTML): converts a specific character to an HTML object into plain text.
* Filter_xss (HTML), use a group of tags to check and clear HTML
* Check_markup (HTML), which is filtered using a filter (which can be customized)
* Drupal_urlencode (URL): encode a specific character as % 0x
* Check_url (URL): clears harmful protocols in the url, such as javascript: runevilJS ()

Usually, the t () function should be used in the output to filter the output, so as to support the drupal multi-language module.
4.2 process mysql statements
You must use the db_query () function to add, delete, query, modify, and delete databases (the usage of drupal7 varies. for details, refer to the relevant materials). The table name must be in braces, in this way, when there is a database prefix, it can be automatically determined. As follows:
/**
* Implementation of hook_cron ().
*/
Function node_cron (){
Db_query ('delete FROM {history} WHERE timestamp <% d', NODE_NEW_LIMIT );
}
?>



4.2.1 Use db_rewrite_ SQL () to keep private data
If the node access module is enabled to control node access permissions, data that is directly identified through db_query () cannot be filtered by Permissions. in this case, db_rewrite_ SQL () is used (), in some node data operations, if the mysql statement does not process the permission section, you must use this function. Example:
$ Result = db_query (db_rewrite_ SQL ("select distinct B. * FROM {blocks} B left join {blocks_roles} r ON B. module = r. module AND B. delta = r. delta WHERE B. theme = '% s' AND B. status = 1 AND (r. rid IN (". db_placeholders ($ rids ). ") OR r. rid is null) order by B. region, B. weight, B. module ", 'B', 'bid'), array_merge (array ($ theme_key), $ rids ));
?>



Chapter 2 and other important Miscellaneous

* Do not modify the drupal core code unless necessary. if any modification is made, it should be recorded in the development document.
* Try to use the default style for HTML display in the module. for example, table (theme ('table', $ header, $ rows), list (theme ('item _ list ', $ items). For example, HTML and CSS should be written in the module rather than dependent on the topic. in this way, the topic cannot be used during topic switching.
* All links must use the l () function, which automatically determines the location of the root directory of the website to avoid dead links after the website migration.
* Access control should be bound to hook_menu as much as possible, and there should be no excessive judgment in the function.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.