Moodle 程序编写准则 - 编码风格

我知道,如果您已经习惯了一种编码风格而我却让您改变它是有一点讨厌的,但比较而言,这比日后所有人都需要去搞清混合风格的Moodle代码要好一些。对于人们使用的任何编码风格都有很多支持和反对的意见,但现在正在使用的风格已经存在了,因此请坚持下去。

缩进应当是4个连续的空格。绝对不要使用制表符。

变量名应当是容易理解、有含义的小写英文单词。如果确实需要两个或以上的单词,请把它们连在一起,但要保持名称尽可能短。对于数组对象,请使用复数名称。[code]好的: $quiz
好的: $errorstring
好的: $assignments (用于数组)
好的: $i (仅用于小型循环)

坏的: $Quiz
坏的: $aReallyLongVariableNameWithoutAGoodReason
坏的: $error_string [/code]常量应当总是大写的,并总是以模块的名称作为前缀。单词之间应当用下划线分隔。define("FORUM_MODE_FLATOLDEST", 1);函数名称应当是简单的英文小写单词,且总是以模块名作为前缀以防止模块之间的冲突。单词之间以下划线分隔。变量如果可能应当总有合理的缺省值。注意在函数名和其后的括号之间没有空格。[code] function forum_set_display_mode($mode=0) {
global $USER, $CFG;

if ( $mode) {
     $USER->mode = $mode;
} else if (empty( $USER->mode)) {
     $USER->mode = $CFG->forum_displaymode;
}

} [/code]语句块必须总是使用大括号(即便是只有一行)。Moodle使用如下风格: if ($quiz->attempts) { if ( $numattempts > $quiz->attempts) { error($strtoomanyattempts, "view.php?id=$cm->id"); } } 字符串应当尽可能用单引号定义以提高速度。$var = 'some text without any variables'; $var = "with special characters like a new line n"; $var = 'a very, very long string with a '.$single.' variable in it'; $var = "some $text with $many variables $within it"; 实用的注释应当尽可能填写,用以解释代码流程和函数与变量的功能。

每个函数和类都应该使用流行的phpDoc格式编写,以便自动生成代码文档。

内嵌注释应使用 // 风格,并且整齐布局,使其能融入代码中并和代码对齐。[code]/**

  • The description should be first, with asterisks laid out exactly
  • like this example. If you want to refer to a another function,
  • do it like this: {@link clean_param()}. Then, add descriptions
  • for each parameter as follows.
  • @param int $postid The PHP type is followed by the variable name
  • @param array $scale The PHP type is followed by the variable name
  • @param array $ratings The PHP type is followed by the variable name
  • @return mixed
    */
    function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {
    if (!$ratings) {
    $ratings = array(); // Initialize the empty array
    if ($rates = get_records(“forum_ratings”, “post”, $postid)) {
    // Process each rating in turn
    foreach ($rates as $rate) {
    …etc [/code]换行可以被大方地使用——把东西分散开看起来会比较清楚。

一般情况下,在花括号和普通命令之间应当有一个换行符,但在花括号和变量或函数之间可以没有换行符:[code] foreach ($objects as $key => $thing) {
process($thing);
}

if ($x == $y) {
$a = $b;
} else if ($x == $z) {
$a = $c;
} else {
$a = $d;
} [/code]