Indenting and Whitespace
Use 2 spaces instead of the tab key for code indentation (notepad++, Eclipse and other editors support this configuration);
There should be no whitespace characters at the end of the line
Use n (Unix newline character), not rn (Windows newline character)
All files should end with a blank line
Operators
All binary operators (operators between two values), such as +, -, =, !=, ==, > etc. , there needs to be a space at both ends of the operator, for example $foo = $bar should be used instead of $foo=$bar.
All unary operators (operators that only operate on one duty), such as ++, should not add spaces between the value and the operator
Casting
A space should be added between (type) and the variable to be cast, such as (int) $mynumber.
Control Structures
Control structures include if, for, while, switch, etc. The following is a simple if statement structure example:
Copy code The code is as follows:
if (condition1 || condition2) {
action1;
}
elseif (condition3 && condition4) {
action2;
}
else {
defaultaction;
}
(Note: Do not use "else if" -- always use elseif.)
There should be a space between the keyword of the control statement and the left parenthesis, This is used to distinguish it from function calls.
Braces should always be used even when they are optional. This can enhance the readability of the code and reduce logic errors caused by nesting.
Switch statement structure example:
Copy code The code is as follows:
switch (condition) {
case 1 :
action1;
break;
case 2:
action2;
break;
default:
defaultaction;
}
do-while statement structure example :
do {
actions;
} while ($condition);
Line length and wrapping (Line length and wrapping)
Usually Under certain circumstances, the length of each line of code should not exceed 80 characters
In the following situations, the line length can exceed 80 characters: when the line contains too long function names, function/class definitions, variable declarations, etc.
For convenience To read and understand, the line length of the control structure can exceed 80 characters
Copy the code The code is as follows:
if ($something ['with']['something']['else']['in']['here'] ==
mymodule_check_something($whatever['else'])) {
...
}
if (isset($something['what']['ever']) && $something['what']['ever'] > $infinite
&& user_access('galaxy')) {
...
}
// Non-obvious conditions of low complexity are also acceptable, but should
// always be documented, explaining WHY a particular check is done.
if (preg_match('@(/|\)(..|~)@', $target) && strpos($target_dir, $repository)
!== 0) {
return FALSE;
}
Control conditions should not be written in multiple lines
Control conditions should be split appropriately to facilitate reading and understanding. When writing code, avoid the following situations:
Copy code The code is as follows:
// DON'T DO THIS!
if ((isset($key) && !empty($user->uid) && $key == $user->uid) || (isset($user-
>cache) ? $user->cache : '') == ip_address() || isset($value) && $value >= time()))
{
...
}
Split the control conditions , not only easy to read, but also convenient to add comments to let people know why such conditional judgment is made
Copy the code The code is as follows:
// Key is only valid if it matches the current user's ID, as otherwise other
// users could access any user's things.
$is_valid_user = (isset($key) && !empty($user-> ;uid) && $key == $user->uid);
// IP must match the cache to prevent session spoofing.
$is_valid_cache = (isset($user->cache) ? $user ->cache == ip_address() : FALSE);
// Alternatively, if the request query parameter is in the future, then it
// is always valid, because the galaxy will implode and collapse anyway.
$is_valid_query = $is_valid_cache || (isset($value) && $value >= time());
if ($is_valid_user || $is_valid_query) {
...
}
Function Calls
When calling a function, there is no space between the function name and the left bracket. Except for the last parameter, each parameter should be followed by a space. , such as:
$var = foo($bar, $baz, $quux);
As mentioned before, there should be a space on both sides of the equal sign. When there is a series of related statements, for the sake of readability, the number of spaces can be appropriately increased, such as:
$short = foo($bar);
$long_variable = foo($baz);
Function Declarations
Parameters containing default values should be placed at the end. When a function has a return value, try to return a value that is easy to understand:
Copy code The code is as follows:
function funstuff_system($field) {
$system["description"] = t("This module inserts funny text into posts randomly.");
return $system[$field];
}
Class Constructor Calls
When When calling a class constructor without parameters, always include the brackets
$foo = new MyClassName();
Class constructor with parameters
$foo = new MyClassName($arg1, $arg2);
If you use a variable as the class name, you need to assign a value to the variable first, and then Call the class constructor:
Copy code The code is as follows:
$bar = 'MyClassName';
$foo = new $bar();
$foo = new $bar($arg1, $arg2);
Array (Array)
Between the values of the array Spaces should be used to separate them, and spaces should also be included around the assignment operator symbol (=>):
$some_array = array('hello', 'world', 'foo' => 'bar');
when If the character length of the declared array exceeds 80 characters (usually when constructing forms and menus), each element should be written in separate lines and indented:
Copy code Code As follows:
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title' ),
'#size' => 60,
'#maxlength' => 128,
'#description' => t('The title of your node.'),
);
注意:最后一个数组元素末尾有一个逗号,这并不是手误,而是避免有新元素加入到最后之后因缺少逗号而出现解析错误。(从某种程度上来讲,在最后一个数组元素末尾加上逗号是一种推荐的做法,甚至在向drupal.org提交代码时,一些代码规范检测脚本会因为最后一个元素没有添加逗号而出现警告提示。)
引号(Quotes)Drupal 对于单引号和双引号的使用并没有很强硬的标准,只需在同一模块内保持用法的统一即可。
使用单引号的效率要高于双引号,因为解析器不需要到引号之间查找变量。以下是使用双引号的两种情况:
引号中间带有变量,如"
$header
"
引号中间带有单引号,使用双引号可避免对单引号的转义 "He's a good person." 当然也可以使用单引号,但 .pot 解析器不能很好的处理这种情况,而且看起来怪怪的'He\'s a good person.'
字符串连接(String Concatenations)
在点与要连接字符串之间需要加入空格以加强代码可读性:
如果只是简单地连接变量,可以使用双引号
使用连接赋值符(.=)时,需要在符号两侧预留空格
注释(Comment)
注释规范单独在 Doxygen及注释格式规范页面 讨论
引入代码(Including Code)
任何无条件引用文件的情况下,使用 require_once(), 任何有条件引用文件的情况,则使用 include_once(). 这两条语句都会保证文件只被引入一次。
当从当前目录或子目录引入代码时,始终以点路径开头
include_once ./includes/mymodule_formatting.inc
在 Drupal 7 及更新版本中,使用 DRUPAL_ROOT 常量:
require_once DRUPAL_ROOT . '/' . variable_get('cache_inc', 'includes/cache.inc');
PHP 代码标签(PHP Code Tags)
始终使用来界定PHP代码而不使用要 ?>。这是为了遵循Drupal规范,同时也便于代码在其它系统和平台中被引用。
自 Drupal 4.7 开始,最后的 ?> 都故意被忽略不写,原因如下:
移除它可以避免在文件末尾出现空白字符,这些空白字符可能导致“文件头已发送(header already sent)”错误,XHTML/XML验证错误,及其它问题
PHP 官方说明 结尾的PHP界定符是可选项
PHP.net 自身也移除了文件末尾的界定符(如 prepend.inc )
分号(Semicolons)
PHP 语言要求除了代码块以外,大多数行尾都要跟上分号。Drupal 代码规范同样有此要求,并且对于代码块也是如此。以下是一个单行代码块的示例:
-- YES
-- NO
示例 URL(Example URL)
使用 example.com 表示所有示例 URLs
命名规范(Naming Conventions)
函数与变量(Functions and Variables)
函数与变量名称应该使用小写字母,且单词之间使用下划线分隔。函数应该使用模块组/模块名称作为前缀,以避免与不同模块间的冲突。
持久变量(Persistent Variables)
持久变量是指通过 variable_get()/variable_set() 函数取得和设置的变量,变量名称应该使用小写字母,且单词之间使用下划线进行分隔。持久变量也应该使用模块组/模块名称作为前缀,以避免与不同模块间的冲突。
常量(Constants)
常量始终要求使用全大写字母,且单词之间使用下划线进行分隔。(包括PHP内置常量 TRUE, FALSE, NULL)
模块中定义的常量需始终使用大写的模块名称作为前缀。
在 Drupal 8 及之后,应使用 const 关键词代替 define() 函数来定义常量,因为效率更高
注意 const 不能用于PHP表达式,因此在条件判断和非字面值(non-literal value ???)时,还是应当使用 define() 函数
全局变量(Global Variables)
定义全局变量时,应当使用下划线加模块/主题名称开头
类(Class)
类名应使用驼峰式命名(即单词首字母大写)
类中的方法(函数)和属性(成员变量)应使用首字母小写的驼峰式
定义访问权限时,使用 protected 而代替 private,从而其它的类可以在必要时扩展和更新方法。Protected 和 public 函数和变量不应以下划线开头。
更多关于 面向对象的编码规范
文件名(Filename)
所有文档文件都应加上 .txt 后缀,以便于 Windows 用户查看。同时,所有文件名称应该全部大写,而文件后缀应该全部小写。
如 README.txt, INSTALL.txt, TODO.txt, CHANGELOG.txt 等等。
Auxiliary modules and tools
Coder module: can follow some of the above code specifications, review the code and make modification suggestions
Drupal Code Sniffer: Code specification detection tool
PAReview.sh : Also handles the code specification detection script in the sandbox, almost strictly abides by all the above code specifications and gives modification suggestions.
http://www.bkjia.com/PHPjc/327453.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327453.htmlTechArticleIndenting and Whitespace Use 2 spaces instead of the tab key for code indentation ( Notepad++, Eclipse and other editors all support this configuration); the end of the line should not be...