コーディングスタイル (Dev docs)

提供:MoodleDocs
2023年4月13日 (木) 07:51時点におけるToshihiro KITA (トーク | 投稿記録)による版 (→‎Namespaces)
移動先:案内検索
重要:

このページの内容は更新され、新しいMoodle Developer Resourcesに移行されました。このページに含まれる情報は、もはや最新であるとみなされるべきではありません。

このページを新サイトで閲覧する そして より多くのコンテンツを新サイトに移行するために協力する というのはいかがでしょうか!


(このページは現在翻訳中です。)

概要

範囲

この文書では、Moodleのコードを扱う開発者向けに、コードのレイアウトのメカニズムと、Moodleで採用した選択肢についての スタイル ガイドラインについて説明します。この仕様の目的は、異なる著者によるコードをスキャンする際の認知的な摩擦を減らすことです。それは、PHPコードをフォーマットするための共有されたルールや期待事項を列挙することによって実現されます。

特に指定がない限り、このコーディングスタイル文書は、順番に PSR-12、そしてPSR-1に従います

de-facto Moodle standard* が文書化されていない場合は、適切な MDLSITE の問題を提起し、そのスタンダードをこのコーディングスタイルガイドに記載するか、PSRの勧告を代わりに採用するようにしてください。

* "de-facto Moodle standard" とは、Moodleで一般的かつ典型的に使用されるコーディングスタイルを指します。

ゴール

どんな開発プロジェクトにおいても、一貫性のあるコーディングスタイルは重要であり、特に多数の開発者が関わる場合には必要不可欠です。標準的なスタイルを採用することで、コードをより読みやすく理解しやすくすることができ、全体的な品質を向上させることができます。

私たちが目指す抽象的な目標:

  • シンプリシティ
  • 読みやすさ
  • ツールの使いやすさ、例えば、IDEツールやメソッド、クラス、定数名の自動補完をサポートするメソッドシグネチャ、定数、パターンの使用。

上記の目標を考慮する場合、各状況に応じて状況を検討し、様々なトレードオフをバランスさせる必要があります。

既存のMoodleのコードの多くが、これらのガイドラインに従っていない可能性があることに注意してください。私たちはそれを見つけ次第、このコードをアップグレードし続けています。

何かを実行するためにMoodle APIを使用する詳細については、コーディングガイドラインを参照してください。

便利なツール

このガイドに従うコードの記述に役立つ、いくつかの異なるツールがあります。

コードチェッカー(eclipse/phpstormと統合
https://moodle.org/plugins/view.php?plugin=local_codechecker
Moodle PHPdocチェッカー
https://moodle.org/plugins/local_moodlecheck

両方のツールを使用して、書いているコードをチェックすることは価値があります。両方とも若干異なるチェックを実行するためです。 両方のチェッカーをパスできるようにすると、あなたの作品を審査する人々と友好的になるための良い道を歩んでいます。

ファイルフォーマット

PHPタグ

常に "long" PHPタグを使用してください。ただし、余分な空白を回避するため、ファイルの最後に閉じるタグを含めないでください。

<?php
require('config.php');

インデント

タブ文字を使用せず、インデントは 4 スペースを使用してください。新しいタブ文字がソースコードに挿入されないように、エディタをタブをスペースとして扱うように設定する必要があります。

メインスクリプトレベルをインデントしないでください:

良い例:

<?php
require('config.php');
$a = required_param('a', PARAM_INT);
if ($a > 10) {
    call_some_error($a);
} else {
    do_something_with($a);
}

悪い例:

<?php
    require('config.php');
    $a = required_param('a', PARAM_INT);
    if ($a > 10) {
        call_some_error($a);
    } else {
        do_something_with($a);
    }

SQLクエリは、SQLコーディングスタイルを参照して特別なインデントを使用します。

最大行長

最も重要な点は可読性です。

132文字を目指すことが望ましく、180文字を超えることは推奨されません。

例外は /lang ディレクトリ内の文字列ファイルで、行 $string['id'] = 'value'; の値は引用符で囲まれた1つの文字列として定義する必要があります(連結演算子、heredoc構文、newdoc構文は使用しない)。これにより、これらの文字列ファイルがPHPコードとして解釈されずに解析および処理できるようになります。

行の折り返し

行を折り返す場合、次のルールが一般的に適用されます。

  • 通常は4スペースでインデントします。
  • 制御文の条件や関数/クラス宣言といった折り返し行は、制御文や関数/クラスの本体と視覚的に区別できるように、4つのスペースでインデントします。

以下のセクションの例を参照してください。

制御構造の折り返し

while ($fileinfolevel && $params['component'] === 'user'
        && $params['filearea'] === 'private') {
    $fileinfolevel = $fileinfolevel->get_parent();
    $params = $fileinfolevel->get_params();
}

if文の条件式の折り返し

特別なことは何もなく、制御構造体の規則が適用されます。

if (($userenrol->timestart && $userenrol->timestart < $limit) ||
        (!$userenrol->timestart && $userenrol->timecreated < $limit)) {
    return false;
}

ただし、1つの制御構造に複数の条件がある場合は、条件式の評価に使用するためのヘルパー変数を設定して、可読性を向上させてください。

$iscourseorcategoryitem = ($element['object']->is_course_item() || $element['object']->is_category_item());
$usesscaleorvalue = in_array($element['object']->gradetype, [GRADE_TYPE_SCALE, GRADE_TYPE_VALUE]);

if ($iscourseorcategoryitem && $usesscaleorvalue) {
    // 条件式がより簡単に見直しと理解ができるようになります。
}

次の例と比較してください。

// 以下は避けるべきです。
if (($element['object']->is_course_item() || $element['object']->is_category_item())
        && ($element['object']->gradetype == GRADE_TYPE_SCALE
        || $element['object']->gradetype == GRADE_TYPE_VALUE)) {
    // 条件が複雑で長い行は、適切にインデントされていても非推奨です。
}

クラス宣言の折り返し

class foo implements bar, baz, qux, quux, quuz, corge, grault,
        garply, waldo, fred, plugh, xyzzy, thud {

    // クラス本体は4スペースでインデントされます。
}

また、読みやすくするために、実装されたインターフェースをそれぞれ1行にまとめて提供することもできます:

class provider implements
        // これらの行は、クラス本体と視覚的に区別するために、8個のスペースでインデントされます。
        \core_privacy\local\metadata\provider,
        \core_privacy\local\request\subsystem\provider,
        \core_privacy\local\request\core_userlist_provider {

    // クラス本体は4スペースでインデントされます。
}

関数シグネチャの折り返し

/**
 * ...
 */
protected function component_class_callback_failed(\Throwable $e, string $component, string $interface,
        string $methodname, array $params) {
    global $CFG, $DB;

    if ($this->observer) {
        // ...
    }
}

関数呼び出しのパラメータの折り返し

通常、パラメータは1行に収まるようになっています。1行に収まらないほど長くなる場合や、読みやすくなる場合は、空白を4つ入れてインデントします。

do_something($param1, $param2, null, null,
    $param5, null, true);

配列の折り返し

特別なことはなく、一般的なルールが再び適用されます。折り返し行を4スペースでインデントします。

$plugininfo['preferences'][$plugin] = ['id' => $plugin, 'link' => $pref_url, 
    'string' => $modulenamestr];

多くの場合、各項目を1行にまとめた以下のようなスタイルが、コードをより読みやすくします。

$plugininfo['preferences'][$plugin] = [
    'id' => $plugin, 
    'link' => $pref_url, 
    'string' => $modulenamestr,
];

最後の項目には末尾のカンマが残っていることに注意してください。これは、後で項目リストを拡張してよりきれいな差分を得ることができるようにするためです。同じ理由で、代入演算子も揃えない方がよいでしょう。

関数のパラメータとして渡される配列の折り返し

これは、上記のいくつかの例を組み合わせたものに過ぎません。

$url = new moodle_url('/course/loginas.php', [
    'id' => $course->id,
    'sesskey' => sesskey(),
]);

行の終端部

  • すべての行は、Unixの改行文字(LF、10進数10、16進数 0x0A)で終了する必要があります。
  • キャリッジリターン(CR、10進数13、16進数 0x0D)は単独または LF と一緒に使用してはいけません。
  • 行末に空白文字(スペースやタブ)を入れてはいけません。
  • ファイルの最後には余分な空白行があってはならず、すべてのファイルは1つの LF 文字で終わる必要があります。

注意: これはPSR-12の規約と一致しています。

命名規則

ファイル名

ファイル名は :

  • 全て英語であること
  • できるだけ短くすること
  • 小文字のみを使用すること
  • .php、.html、.js、.css、.xmlのいずかで終わること

クラス

クラス名は必ず小文字の英単語で、アンダースコアで区切ってください:

class some_custom_class {
    function class_method() {
        echo 'foo';
    }
}

コンストラクタがパラメータを必要としない場合でも、新しいインスタンスを作成するときは常に()を使用します。

$instance = new some_custom_class();

例えば、$DB->insert_recordでデータベースに挿入するデータを準備するときなど、特定のクラスのないプレーンなオブジェクトが欲しいときは、PHP標準クラス stdClass を使用する必要があります。 例:

$row = new stdClass();
$row->id = $id;
$row->field = 'something';
$DB->insert_record('table', $row);

Moodle 2.0以前では、私たちはstdClassを拡張したクラス object を定義し、new object() を使用していました; これは現在非推奨です。代わりに stdClass を使用してください。

関数および手法

関数名は単純な英語の小文字の単語で、プラグイン間の衝突を避けるために Frankenstyle のプレフィックスとプラグイン名で始まるようにします。単語はアンダースコアで区切られる必要があります。

冗長性が奨励されます: 関数名は、理解を深めるために、できるだけ具体的に説明することが望ましいです。

PHPでは、すべての新しいコードに対して、タイプヒントと戻り値の宣言の使用が可能なすべての場所で要求されています。既存の非準拠なコードを拡張するコードや、利用できないものを実装するコードなど、必要な除外項目があるものとします。プログレッシブ・アプローチが適用されます。

関数名と次の(括弧)の間にスペースがないことに注意してください。また、Nullable文字(クエスチョンマーク - ?)とパラメータやリターンタイプの間、関数の閉じ括弧とコロンの間にも空白がありません。

function report_participation_get_overviews(string $action, ?int userid): ?array {

    // 実際のファンクションコードはここに入ります。
}

ただし、レガシーな理由でプラグイン名のみをプレフィックスとして使用している活動モジュールは例外です。

function forum_set_display_mode($mode = 0) {
    global $USER, $CFG;
         
    // 実際のファンクションコードはここに入ります。
}

関数パラメータ

パラメーターは常に単純な小文字の英単語($initialvalueのように複数の場合もあります)であり、可能な場合は常に適切なデフォルト値を持つべきです。

このようにデフォルト値が必要ない場合は、"false" の代わりに "null" をデフォルト値として使用します。

public function foo($required, $optional = null)

ただし、オプションのパラメータが boolean であり、その論理的なデフォルト値が true または false である場合は、true または false を使用しても構いません。

変数

変数名は常に読みやすく、意味がある小文字の英単語でなければなりません。もし1つ以上の単語が必要な場合は、連結して書くことができますが、できるだけ短く保つようにしてください。オブジェクトの配列には、複数形 の名前を使用してください。そして、変数名には、常に 肯定的 な言葉を使うようにしてください。(例えば、prevent や disable ではなく、allow や enable などです。

GOOD: $quiz
GOOD: $errorstring
GOOD: $assignments (for an array of objects)
GOOD: $i (but only in little loops)
GOOD: $allowfilelocking = false
BAD: $Quiz
BAD: $camelCase
BAD: $aReallyLongVariableNameWithoutAGoodReason
BAD: $error_string
BAD: $preventfilelocking = true

Moodleのコアグローバル変数は、大文字の変数 (例 $CFG、$SESSION、$USER、$COURSE、$SITE、$PAGE、$DBおよび$THEME) を使用して識別します。 これ以上作らないでください!

定数

定数は常に大文字で、常に Frankenstyle のプレフィックスとプラグイン名で始まります(レガシーな理由からモジュール名のみで活動する場合)。単語はアンダースコアで区切ってください。

define('BLOCK_COURSE_OVERVIEW_SHOWCATEGORIES_NONE', '0');
define('FORUM_MODE_FLATOLDEST', 1);

ブーリアンおよびヌル値

truefalsenullは小文字を使用してください。

名前空間

Moodleの新しいクラスには、正式な名前空間が必要です。ただし、以下の例外があります:

  1. 既存の非名前空間クラスを名前空間に移動させる必要はありません; また
  2. クラスを読み込むための既存のメカニズムが存在し、そのメカニズムが名前空間クラスの使用をサポートしていない場合、クラス名に既存の Frankenstyle プレフィックスを使用することが許可されます。

クラス名に対するクラス名のFrankenstyleプレフィックスの使用は非推奨であり、上記の例外においてのみ使用されるべきである。

GOOD:

namespace mod_forum;
class example {
}
 
namespace mod_forum\external;
class example {
}
 
namespace core_user;
class example {}

BAD (deprecated):

class mod_forum_example {
}
 
class mod_forum_external_example {
}
 
class core_user_example {
}

The use of namespaces must conform to the following rules:

  1. Classes belonging to a namespace must be created in a classes directory inside a plugin (e.g. mod/forum/classes), or for core code, in lib/classes or subsystemdir/classes.
  2. The classname and filename for all namespaced classes must conform to the automatic class loading rules. The use of formal PHP namespaces in all new code is required.
  3. Use at most one namespace declaration per file.

GOOD:

<? // This is a file mod/porridge/classes/local/equipment/spoon.php

namespace mod_porridge\local\equipment;

class spoon {
    // Your code here.
}

// End of file.

BAD:

namespace mod_porridge\local\equipment;

class spoon {
    // Your code here.
}

namespace mod_porridge\local\procedures; // We are changing the namespace here, do not do it.

class eat {
    // Another code here.
}

// End of file.

The namespace declaration may be preceded with a doc block.

The class naming rules also apply to the names for each level of namespace.

The namespace declaration must be the first non-comment line in the file, followed by one blank line, followed by the (optional) "use" statements, one per line, followed by one blank line.

"use" statements should be used to avoid repetition of long namespaces in the code.

Do not import an entire namespace with a "use" statement, import individual classes only.

Do not use named imports ("use XXX as YYY;") unless it is absolutely required to resolve a conflict.

GOOD:

use mod_porridge\local\equipment\spoon; // One class per line.
use mod_porridge\local\equipment\bowl; // One class per line.

BAD:

use mod_porridge\local\equipment\spoon, mod_porridge\local\equipment\bowl; // Multiple classes per line.
use mod_porridge\local; // Importing an entire namespace.
use core; // Importing an entire namespace.
use mod_breakfast; // Importing an entire namespace.
use mod_porridge\local\equipment\spoon as silverspoon; // Named import with no good reason.

Never use the __NAMESPACE__ magic constant.

Never use the "namespace" keyword anywhere but the namespace declaration.

BAD:

$obj = new namespace\Another();

Do not use bracketed "namespace" blocks.

BAD:

namespace {
    // Global scope.
}

Namespaces MUST only be used for classes existing in a subfolder of "classes".

For new classes - the maximum level of detail should be used when deciding the namespace.

GOOD:

namespace xxxx\yyyy; // xxxx is the component, yyyy is the api.

class zzzz {
}

Never use a leading backslash (\) in "namespace" and "use" statements.

Global functions called from namespaced code should never use a leading backslash (\). Classes from outside the current scope use the leading backslash or are imported by the "use" keyword. See PHP manual for details.

GOOD:

namespace mod_breakfast\local;

use moodle_url;

echo get_string('goodmorning', 'mod_breakfast'); // No leading backslash for global functions.
$url = new moodle_url(...); // Leading backslash not needed here because we imported it into our namespace via "use".
$tasks = \core\task\manager::get_all_scheduled_tasks(); // Leading slash needed here.
$a = new \stdClass(); // Leading slash needed here.

BAD:

namespace \mod_breakfast; // The leading backslash should not be here.

use \core\task\manager; // The leading backslash should not be here.

\get_string('xxxx', 'yyyy'); // The leading backslash should not be here.

Parts of a namespace

Given the following fully qualified name of a class:

"\<level1>\<level2>\<level3>\...\<classname>"

There are clear rules for what is allowable at each level of namespace. Only the first level is mandatory. Nested namespaces are used when the class implements some core API or when the plugin maintainer want to organise classes to separate namespaces within the plugin - see rules regarding the level2 for details.

Rules for level1

The first level MUST BE EITHER:

  • a full component name (e.g. "\mod_forum"). All classes using namespaces in a plugin MUST be contained in

this level 1 namespace. or

  • "\core" for all core apis

Rules for level2

The second level, when used, MUST BE EITHER:

  • The short name of a core API (must be defined on https://docs.moodle.org/dev/API). The classes in this namespace must either implement or use the API in some way.

or

  • "\local" for any other classes in a component, if the maintainer wants to organise them further (note that for most components, it's probably enough to have all their own classes in the root level1 namespace only).

Rules for level3

There are no rules limiting what can be used as a level 3 namespace. This is where a plugin or addon can make extensive use of namespaces with no chance of conflict with any other plugin or api, now and forever onwards.

Namespaces within **/tests directories

(agreed @ MDLSITE-4800)

  • The use of namespaces is strongly recommended for unit tests.
  • When using namespaces, the namespace of the test class should match the namespace of the code under test.
  • Test classes should be named after the class under test, and suffixed with `_test.php`.
  • The 1st level namespace of the test class must match the component it belongs to.
  • Sub-namespaces are allowed, strictly following the general namespace rules for levels 2 & 3 above. Always trying to match as much as possible the namespace of the code being covered.
  • Sub-directory structure must match the namespace structure, but will be placed in the `tests` directory instead.

Please note: auto-loading of tests is not supported (but autoloading the standard class from a test is).

Examples

GOOD:

// Plugin's own namespace when not using nested namespaces (typical)
// Namespace location: mod/breakfast/classes/
// Test location: mod/breakfast/tests/
namespace mod_breakfast;

// Plugin's own namespace when using nested namespaces
// Namespace location: mod/breakfast/classes/local/
// Test location: mod/breakfast/tests/local/
namespace mod_breakfast\local;

// Plugin's own namespace when using nested namespaces with further organisation
// Namespace location: mod/breakfast/classes/local/utils/
// Test location: mod/breakfast/tests/local/utils/
namespace mod_breakfast\local\utils;

// Plugin's namespace to implement core API
// Namespace location: mod/breakfast/classes/event/
// Test location: mod/breakfast/tests/event/
namespace mod_breakfast\event;

BAD:

namespace mymodule;                     // Violates the level1 rules - invalid component name
namespace mod_breakfast\myutilities;    // Violates the level2 rules - invalid core API name
namespace mod_forum\test;               // While technically correct ("test" is a valid API) - it's not ok
                                        // because the namespace in tests should match the namespace of the code
                                        // being covered, and normally components don't have any "test"
                                        // level-2 to be covered. Only then it could be used.

Strings

Since string performance is not an issue in current versions of PHP, the main criteria for strings is readability.

Single quotes

Always use single quotes when a string is literal, or contains a lot of double quotes (like HTML):

$a = 'Example string'; 
echo '<span class="'.s($class).'"></span>'; 
$html = '<a href="http://something" title="something">Link</a>';

Double quotes

These are a lot less useful in Moodle. Use double quotes when you need to include plain variables or a lot of single quotes.

echo "<span>$string</span>"; 
$statement = "You aren't serious!";

Complex SQL queries should be always enclosed in double quotes.

$sql = "SELECT e.*, ue.userid
          FROM {user_enrolments} ue
          JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
          JOIN {user} u ON u.id = ue.userid
         WHERE :now - u.lastaccess > e.customint2";

Variable substitution

Variable substitution can use either of these forms:

$greeting = "Hello $name, welcome back!";

$greeting = "Hello {$name}, welcome back!";

String concatenation

Strings must be concatenated using the "." operator.

$longstring = $several.$short.'strings';

If the lines are long, break the statement into multiple lines to improve readability. In these cases, put the "dot" at the end of each line.

$string = 'This is a very long and stupid string because '.$editorname.
          " couldn't think of a better example at the time.";

The dot operator may be used without any space to either side (as shown in the above examples), or with spaces on each side; whichever the developer prefers.

Language strings

Capitals

Language strings should "Always look like this" and "Never Like This Example".

Capitals should only be used when:

  1. starting a sentence, or
  2. starting a proper name, like Moodle.

Structure

Strings should not be designed for UI concatenation, as it may cause problems in other languages. Each string should stand alone.

BAD:

$string['overduehandling'] = 'When time expires';
$string['overduehandlingautosubmit'] = 'the attempt is submitted automatically';
$string['overduehandlinggraceperiod'] = 'there is a grace period in which to submit the attempt, but not answer more questions';
$string['overduehandlingautoabandon'] = 'that is it. The attempt must be submitted before time expires, or it is not counted';

GOOD:

$string['overduehandling'] = 'Time expiry behaviour';
$string['overduehandlingautosubmit'] = 'Unfinished attempts will be auto-submitted immediately';
$string['overduehandlinggraceperiod'] = 'Unfinished attempts have a short grace period to be submitted for grading';
$string['overduehandlingautoabandon'] = 'Unfinished attempts are immediately discarded';

Whitespace

Language strings should not contain or even rely on any leading or trailing whitespace. Such strings are not easy to be translated in the translation tool, AMOS.

Arrays

Numerically indexed arrays

When declaring arrays, a trailing space must be added after each comma delimiter to improve readability:

$myarray = [1, 2, 3, 'Stuff', 'Here'];

Multi-line indexed arrays are fine, but pad each successive lines as above with an 4-space indent:

$myarray = [1, 2, 3, 'Stuff', 'Here',
    $a, $b, $c, 56.44, $d, 500];

Note that the example above also can be written as follows:
(with special attention to the last line having a trailing comma to extend the list of items later with a cleaner diff)

$myarray = [
    1, 2, 3, 'Stuff', 'Here',
    $a, $b, $c, 56.44, $d, 500,
];

In any case, brackets and newlines need to be balanced, irrespectively of the number of elements per line.

Associative arrays

Use multiple lines if this helps readability. For example:

$myarray = [
    'firstkey' => 'firstvalue',
    'secondkey' => 'secondvalue',
];

Classes

Class declarations

  • Classes must be named according to Moodle's naming conventions.
  • Classes must go under their respective "component/classes" dir to get the benefits of autoloading and namespacing. There aren't such luxuries out from there.
  • Each php file will contain only one class (or interface, or trait...). Unless it's part of old APIs where multi-artifact files were allowed.
  • The brace should always be written on the line beside the class name.
  • Every class must have a documentation block that conforms to the PHPDocumentor standard.
  • All code in a class must be indented with 4 spaces.
  • Placing additional code ("side-effects") in class files is only permitted to require artifacts not provided via autoloading (old classes or libs out from the "classes" directories and not loaded by Moodle's bootstrap). In those cases, the use of the MOODLE_INTERNAL check will be required.
An example:
/**
 * Short description for class.
 *
 * Long description for class (if any)...
 *
 * @package    mod_mymodule
 * @copyright  2008 Kim Bloggs
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class sample_class {
    // All contents of class
    // must be indented 4 spaces.
}

Note the classes PHPDoc style is defined with more detail in the Documentation and comments / Classes section in this document.

Class member variables

Member variables must be named according to Moodle's variable naming conventions.

Any variables declared in a class must be listed at the top of the class, above the declaration of any methods.

The var construct is not permitted. Member variables always declare their visibility by using one of the private, protected, or public modifiers. Giving access to member variables directly by declaring them as public is permitted but discouraged in favor of accessor methods (set/get).

Functions and methods

Function and method declaration

Functions must be named according to the Moodle function naming conventions.

Methods inside classes must always declare their visibility by using one of the private, protected, or public modifiers.

As with classes, the brace should always be written on same line as the function name.

Don't leave spaces between the function name and the opening parenthesis for the arguments.

The return value must not be enclosed in parentheses. This can hinder readability, in additional to breaking code if a method is later changed to return by reference.

Return should only be one data type. It is discouraged to have multiple return types

/**
 * Documentation Block Here
 */
class sample_class {
    
    /**
     * Documentation Block Here
     */
    public function sample_function() {
        // All contents of function
        // must be indented four spaces.
        return true;
    }
}

Function and method usage

Function arguments should be separated by a single trailing space after the comma delimiter.

three_arguments(1, 2, 3);

Magic methods

Magic methods are heavily discouraged, justification will be required when used. Note: lazyness will not be a valid argument.

(See MDL-52634 for discussion of rationale)

Control statements

In general, use white space liberally between lines and so on, to add clarity.

If / else

Put a space before and after the control statement in brackets, and separate the operators by spaces within the brackets. Use inner brackets to improve logical grouping if it helps.

Indent with four spaces.

Don't use elseif!

Always use braces (even if the block is one line and PHP doesn't require it). The opening brace of a block is always placed on the same line as its corresponding statement or declaration.

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

Switch

Put a space before and after the control statement in brackets, and separate the operators by spaces within the brackets. Use inner brackets to improve logical grouping if it helps.

Always indent with four spaces. Content under each case statement should be indented a further four spaces.

switch ($something) {
    case 1:
        break;

    case 2:
        break;

    default:
        break;
}

Foreach

As above, uses spaces like this:

foreach ($objects as $key => $thing) {
    process($thing);
}

Ternary Operator

The ternary operator is only permitted to be used for short, simple to understand statements. If the statement can't be understood in one sentance, use an if statement instead.

Whitespace must be used around the operators to make it clear where the operation is taking place.

GOOD:

$username = isset($user->username) ? $user->username : ''; **
$users = is_array($users) ? $users : [$users];

BAD:

$toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
$coefstring = ($coefstring=='' or $coefstring=='aggregationcoefextrasum') ? 'aggregationcoefextrasum' : 'aggregationcoef';

** Note that, since PHP 7.0, many of those "isset()" ternaries can be changed to use the new shorthand null coalescing operator so, the above is equivalent to:

$username = $user->username ?? '';

Require / include

Each file that is accessed via browser should start by including the main config.php file.

require(__DIR__ . '/../../config.php');

Any other include/require should use a path starting with __DIR__ or an absolute path starting with $CFG->dirroot or $CFG->libdir. Relative includes starting with "../" can sometimes behave strangely under PHP, so should not be used. Our CLI scripts must not use relative config.php paths starting with "../".

For library files in normal usage, require_once should be used (this is different from config.php which should always use 'require' as above). Examples:

require_once(__DIR__ . '/locallib.php');
require_once($CFG->libdir . '/filelib.php');

Includes should generally only be done at the top of files or inside functions/methods that need them. Using include/require in the middle of a file in global scope very hard to audit the security of the code.

All other scripts with the exception of imported 3rd party libraries and files without side-effects* (i.e. single class definitions, interfaces or traits), should use following code at the very top to prevent direct execution which might reveal error messages on misconfigured production servers.

defined('MOODLE_INTERNAL') || die();

*side-effects: Any global scope code not being: a) namespace and use statements or b) namespace constants or c) strict_types declarations (declarations in general).

Please note that the existence or absence of side-effects in a file only affects as explained above, at code level. It shouldn't be considered in other parts of the coding style unless specifically mentioned.

Documentation and comments

Code documentation explains the code flow and the purpose of functions and variables. Use it whenever practical.

PHPDoc

Moodle stays as close as possible to "standard" PHPDoc format to document our files, classes and functions. This helps IDEs (like Netbeans or Eclipse) work properly for Moodle developers, and also allows us to generate web documentation automatically.

PHPDoc has a number of tags that can be used in different places (files, classes and functions). We have some particular rules for using them in Moodle that you must follow:

Types

Some of the tags below (@param, @return...) do require the specification of a valid php type and a description. All these are allowed:

  • PHP primitive types: int, bool, string...
  • PHP complex types: array, stdClass (not Array, object).
  • PHP classes:full or relative (to current namespace) class names.
  • true, false, null (always lowercase).
  • static: for methods returning a new instance of the child/caller class.
  • self: for methods returning a new instance of the parent/called class.
  • $this: for methods returning the current instance of the class.
  • void: for methods with a explicit empty "return" statement.

Also, there are some basic rules about how to use those types:

  • We use short type names (bool instead of boolean, int instead of integer).
  • With cases represented as array of given type, it's highly recommended to document them as type[] instead of the simpler and less informative "array" alternative (e.g. int[] or stdClass[]).
  • When multiple different types are possible, they must be separated by a vertical bar (pipe) (e.g. @return int|false).
  • All primitives and keywords must be lowercase. The case of the complex types and classes must match the original.

Tags

@copyright

These include the year and copyright holder (creator) of the original file. Do not change these in existing files!

 @copyright 2008 Kim Bloggs
@license

These must be GPL v3+ and use this format:

 @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
@param

Don't put hyphens or anything fancy after the variable name, just a space.

 @param type $name Description.
@return

The @return tag is mandatory if the function has a return statement, but can be left out if it does not have one.

The description portion is optional, it can be left out if the function is simple and already describes what is returned.

 @return type Description.
@var

The @var tag is used to document class properties.

 @var type Description.

Exceptionally, when none of the available types define the returned value, inline @var phpdocs (within the body of the methods) providing type hinting are allowed to the returned type. Don't abuse!

@uses

If a function uses die or exit, please add this tag to the docblock to help developers know this function could terminate the page:

 @uses exit
@access

The access can be used to specify access control for an element

  1. Should only be used when the method definition does not already specify access control.
  2. In the case of functions, specifying public access is redundant and so should be avoided.
 @access private
@package

The package tag should always be used to label php files with the correct Frankenstyle component name. Full rules are explained on that page, but in summary:

  1. If the file is part of any component plugin, then use the plugin component name (eg mod_quiz or gradereport_xls)
  2. If the file is part of a core subsystem then it will be core_xxxx where xxxx is the name defined in get_core_subsystems(). (eg core_enrol or core_group)
  3. If the file is one of the select few files in core that are not part of a subsystem (such as lib/moodlelib.php) then it just as a package of core.
  4. Each file can only be part of ONE package.

(We do not have standards for @subpackage at all. You can use within your @package how you like.)

 @package gradereport_xls
@category

We use @category only to highlight the public classes, functions or files that are part of one of our Core APIs, or that provide good example implementations of a Core API. The value must be one of the ones on the Core APIs page.

 @category preferences 
@since

When adding a new classes or function to the Moodle core libraries (or adding a new method to an existing class), use a @since tag to document which version of Moodle it was added in. For example:

 @since Moodle 2.1
@see

If you want to refer the user to another related element (include, class, function, define, method, variable), but not to URLs, then you can use @see.

 @see some_other_function()

This tag can be used inline too, within phpdoc comments.

  /**
   * This function uses {@see get_string()} to obtain the currency names...
   * .....
@link

If you want to refer the user to an external URL, but not to related elements, use @link.

 @link https://docs.moodle.org/dev/Core_APIs

This tag can be used inline too, within phpdoc comments.

  /**
   * For details about the implementation below, visit {@link https://docs.moodle.org/dev/Core_APIs} and read...
   * .....
@deprecated (and @todo)

When deprecating an old API, use a @deprecated tag to document which version of Moodle it was deprecated in, and add @todo and @see if possible. Make sure to mention relevant MDL issues. For example:

/**
 * ...
 * @deprecated since Moodle 2.0 MDL-12345 - please do not use this function any more.   
 * @todo MDL-22334 This will be deleted in Moodle 2.2.
 * @see class_name::new_function()
 */

If it is important that developers update their code, consider also adding a debugging('...', DEBUG_DEVELOPER); call to repeat the deprecated message. If the old function can no longer be supported at all, you may have to throw a coding_exception. There are examples of the various options in lib/deprecatedlib.php.

@throws

This tag is valid and can be used optionally to indicate the method or function will throw and exception. This is to help developers know they may have to handle the exceptions from such functions.

Other specific tags

There are some tags that are only allowed within some contexts and not globally. More precisely:

  • @Given, @When, @Then, within the behat steps definitions.
  • @covers, @coversDefaultClass, @coversNothing, @uses to better control coverage within unit tests.
  • @dataProvider and @testWith, to provide example data and expectations, within unit tests.
  • @depends, to express dependencies between tests, where each producer returned data in passed to consumers. See @depends examples for more information.
  • @group, for easier collecting unit tests together, following the guidelines in the PHPUnit MoodleDocs.
  • @requires, to specify unit test requirements and skip if not fulfilled. See @requires usages for more information.
  • @runTestsInSeparateProcesses and @runInSeparateProcess, to execute an individual test or a testcase in isolation. To be used only when strictly needed.

Files

All files that contain PHP code should contain, without any blank line after the php open tag, a full GPL copyright statement at the top, plus a SEPARATE docblock right under it containing a:

  1. short one-line description of the file
  2. longer description of the file
  3. @package tag (required)
  4. @category tag (only when everything in the file is related to one of the Core APIs)
  5. @copyright (required)
  6. @license (required)

For files containing only one artifact, the file phpdc block is optional as long as the artifact (class, interface, trait...) is documented. Read the following "Classes" section about that case.

<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.

/**
 * This is a one-line short description of the file.
 *
 * You can have a rather longer description of the file as well,
 * if you like, and it can span multiple lines.
 *
 * @package    mod_mymodule
 * @category   backup
 * @copyright  2008 Kim Bloggs
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

Classes

All classes must have a complete docblock like this:

/**
 * Short description for class.
 *
 * Long description for class (if any)...
 *
 * @package    mod_mymodule
 * @category   backup
 * @copyright  2008 Kim Bloggs
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class policy_issue {

For files containing only one artifact (class, interface, trait...), specifically for all the files within classes directories, but also any other file fulfilling the condition anywhere else, it will be enough with the class phpdoc block. The file phpdoc block will be considered optional at all effects, giving to the class one precedence.

The @package, @copyright and @license tags (and the optional @category tag ), as shown in the example above, must be present always in the file (in whichever docblock, but all together).

Properties

All properties should have a docblock with the following minimum information:

class example {
    /** @var string This variable does something */
    protected $something;
}

or

class example {
    /** 
     * This variable does something and has a very long description which can
     * wrap on multiple lines
     * @var string 
     */
    protected $something;
}

Even if there are several properties all sharing something in common, do not use DocBlock templates. Instead, document every property explicitly as in the following example:

class zebra {
    /** @var int The number of white stripes */
    protected $whitestripes = 0;

    /** @var int The number of black stripes */
    protected $blackstripes = 0;

    /** @var int The number of red stripes */
    protected $redstripes = 0;
}

Constants

Class constants should be documented in the following way:

class sam {
   /**
    * This is used when Sam is in a good mood.
    */
   const MOOD_GOOD = 0;
}


Functions

All functions and methods should have a complete docblock like this:

/**
 * The description should be first, with asterisks laid out exactly
 * like this example. If you want to refer to a another function,
 * use @see as below.   If it's useful to link to Moodle
 * documentation on the web, you can use a @link below or also 
 * inline like this {@link https://docs.moodle.org/dev/something}
 * Then, add descriptions for each parameter and the return value as follows.
 *
 * @see clean_param()
 * @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 bool A status indicating success or failure
 */

You must include a description even if it appears to be obvious from the @param and/or @return lines.

An exception is made for overridden methods which make no change to the meaning of the parent method and maintain the same arguments/return values. In this case you should omit the comment completely. Use of the @inheritdoc or @see tags is explicitly forbidden as a replacement for any complete docblock.

Defines

All defines should be documented in the following way:

/**
 * PARAM_INT - integers only, use when expecting only numbers.
 */
define('PARAM_INT', 'int');

/**
 * PARAM_ALPHANUM - expected numbers and letters only.
 */
define('PARAM_ALPHANUM', 'alphanum');

Inline comments

Inline comments must use the "// " (2 slashes + whitespace) style, laid out neatly so that it fits among the code and lines up with it. The first line of the comment must begin with a capital letter (or a digit, or '...') and the comment must end with a proper punctuation character. Permitted final characters are '.', '?' or '!'.

function forum_get_ratings_mean($postid, $scale, $ratings = null) {
    if (!$ratings) {

        $ratings = [];     // Initialize the empty array.

        $rates = $DB->get_records('forum_ratings', ['post' => $postid)];

        // ... then process each rating in
        // turn.
        foreach ($rates as $rate) {
            do_something_with($rate);
        }

        // Do we need to tidy up?
        if (!empty($rates))
            // 42 more things happen here!
            finsh_up();
        }

GOOD:

// Comment explaining this piece of code.

BAD:

/*  Comment explaining this piece of code. */
# Comment explaining this piece of code. 
// comment explaining this piece of code (without capital letter and punctuation)


If your comment is due to some MDL issue, please feel free to include the correct MDL-12345 in your comment. This makes it easier to track down decisions and discussions about things.

Using TODO

This is especially important if you know an issue still exists in that code that should be dealt with later. Use a TODO along with a MDL code to mark this. For example:

// TODO MDL-12345 This works but is a bit of a hack and should be revised in future.

If you have a big task that is nearly done, apart a few TODOs, and you really want to mark the big task as finished, then you should file new tracker tasks for each TODO and change the TODOs comments to point at the new issue numbers.

There is a nice "todo checker" reporting tool, restricted to admins and available via web @ lib/tests/other/todochecker.php.

Finally, don't forget to add any MDL-l2345 used by your TODOs (and @todos too, unless part of the deprecation process, those are handled apart) to the "Review TODOs Epic" : MDL-47779 (requires login to see the issues)

CVS keywords

We have stopped using CVS keywords such as $Id$ in Moodle 2.0 completely.

Exceptions

Use exceptions to report errors, especially in library code.

Throwing an exception has almost exactly the same effect as calling print_error(), but it is more flexible. For example, the caller can choose to catch the exception and handle it in some way. It also makes it easier to write unit tests.

Note that, since 2021, it has been agreed to deprecate print_error() and, instead, to throw moodle_exception() is the correct way to proceed.

Any exception that is not caught will trigger an appropriate call to print_error, to report the problem to the user. Exceptions "error codes" will be translated only when they are meant to be shown to final users.

Do not abuse exceptions for normal code flow. Exceptions should only be used in erroneous situations.

Exception classes

We have a set of custom exception classes. The base class is moodle_exception. You will see that the arguments you pass to new moodle_exception(...) are very similar to the ones you would pass to print_error. There are more specific subclasses for particular types of error.

To get the full list of exception types, search for the regular expression 'class +\w+_exception +extends' or ask your IDE to list all the subclasses of moodle_exception.

Where appropriate, you should create new subclasses of moodle_exception for use in your code.

A few notable exception types:

moodle_exception
base class for exceptions in Moodle. Use this when a more specific type is not appropriate.
coding_exception
thrown when the problem seems to be caused by a developer's mistake. Often thrown by core code that interacts with plugins. If you throw an exception of this type, try to make the error message helpful to the plugin author, so they know how to fix their code.
dml_exception (and subclasses)
thrown when a database query fails.
file_exception
thrown by the File API.

Dangerous functions and constructs

PHP includes multiple questionable features that are highly discouraged because they are very often source of serious security problems.

  1. do not use eval() function - language packs are exception (to be solved in future).
  2. do not use preg_replace() with /e modifier - use callbacks in order to prevent unintended PHP execution.
  3. do not use backticks for shell command execution.
  4. do not use goto, neither the operator neither labels - use other programming techniques to control the execution flow.

Policy about coding-style only fixes

Way before this coding-style guide was defined and agreed, a lot of code had been written already. Obviously such code does not follow the coding-style at all. While we enforce conformance for all the new code, we are not paranoid about the status of all the previous one.

In any case, in order to normalize the (progressive, non-critical) transition, a policy issue (MDL-43233) was created and agreed about. And these are the rules to apply to coding-style only changes:

  1. Related coding-style changes (same lines, a variable within a method/function, adjacent comments...) within a real issue are allowed.
  2. Unrelated coding-style changes (other methods, blocks of code, comments...) within a real issue are only accepted for master and in a separate commit.
  3. Coding-style only issues are only accepted for master along the first 2 months of every cycle.

Git commits

Constructing a clear and informative commit is an important aspect of the craft of creating open source code and the history of commits is a vital part of the communication between developers. Time should be spent on crafting commits appropriately and using the git tools to achieve it.

Git commits should:

  • Tell a perfect, cleaned up version of the history. As if the code was written perfectly first time.
  • Include the MDL-xxxx issue number associated with the change
  • Include CODE AREA when appropriate. (Code area, is just a short name for the area of Moodle that this change affects. It can be a component name if that makes sense, but does not have to be. Remember that your audience here is humans not computers, so if a shortened version of a component name is more readable and distinctive, use that instead.)
  • Be formatted as:
MDL-xxxx CODE AREA: short summary (72 chars soft limit)

Blank line on line 2, followed by an unlimited length detailed explanation
following if necessary. This section might include the motivation for the change
and contrast it with the previous behaviour.

Git commits should not:

  • Include changes from bugs found and fixed before integration
  • Include many separate revisions to the same lines of code for a single issue
  • Arbitrarily split when part of a atomic set of logical changes

For more guidance, see Commit cheat sheet

Credits

This document was drawn from the following sources:

  1. The original Coding guidelines page
  2. The Zend guidelines and
  3. Feedback from all core Moodle developers

関連項目