Coding style

Jump to: navigation, search




This document describes style guidelines for developers working on or with Moodle code. It talks purely about the mechanics of code layout and the choices we have made for Moodle.

For details about using the Moodle API to get things done, see the coding guidelines.


Consistent coding style is important in any development project, and particularly when many developers are involved. A standard style helps to ensure that the code is easier to read and understand, which helps overall quality.

Abstract goals we strive for:

  • simplicity
  • readability
  • tool friendliness, such as use of method signatures, constants, and patterns that support IDE tools and auto-completion of method, class, and constant names.

When considering the goals above, each situation requires an examination of the circumstances and balancing of various trade-offs.

Note that much of the existing Moodle code may not follow all of these guidelines - we continue to upgrade this code when we see it.

Useful tools

There are a couple of different tools available to help you in writing code that conforms to this guide.

Code checker (integrates with eclipse/phpstorm)
Marina Glancy's Moodle PHPdoc checker

It is worth using both tools to check the code you are writing as they both perform slightly different checks. If you can get your code to pass both then you are well on the way to making friends with those who will be reviewing your work.

File Formatting

PHP tags

Always use "long" php tags. However, to avoid whitespace problems, DO NOT include the closing tag at the very end of the file.



Use an indent of 4 spaces with no tab characters. Editors should be configured to treat tabs as spaces in order to prevent injection of new tab characters into the source code.

Don't indent the main script level:


$a = required_param('a', PARAM_INT);
if ($a > 10) {
} else {


    $a = required_param('a', PARAM_INT);
    if ($a > 10) {
    } else {

SQL queries use special indentation, see SQL coding style.

Maximum Line Length

The key issue is readability.

Aim for 132 characters if it is convenient, it is not recommended to use more than 180 characters.

The exception are string files in the /lang directory where lines $string['id'] = 'value'; should have the value defined as a single string of any length, wrapped by quotes (no concatenation operators, no heredoc and no newdoc syntax). This helps to parse and process these string files without including them as a PHP code.

Wrapping lines

Whenever wrapping lines, following rules should generally apply:

  • Indent with 4 spaces by default.
  • Indent the wrapped line with control statement conditions or a function/class declaration with 4 additional spaces to visually distinguish it from the following body of the control statement or the function/class.

See examples in the following sections.

Wrapping control structures

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

Wrapping if-statement conditions

There is nothing special and the control structures rule would still apply.

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

However, if you have a few conditions in one control structure, try setting some helper variables for evaluating the conditions to improve the readability.

$iscourseorcategoryitem = ($element['object']->is_course_item() || $element['object']->is_category_item());
$usesscaleorvalue = in_array($element['object']->gradetype, array(GRADE_TYPE_SCALE, GRADE_TYPE_VALUE));
if ($iscourseorcategoryitem && $usesscaleorvalue) {
    // This makes the conditions easier to review and understand.

Compare it with the following.

if (($element['object']->is_course_item() || $element['object']->is_category_item())
        && ($element['object']->gradetype == GRADE_TYPE_SCALE
        || $element['object']->gradetype == GRADE_TYPE_VALUE)) {
    // Too long lines with complex conditions are discouraged even when they are indented properly.

Wrapping class declarations

class foo implements bar, baz, qux, quux, quuz, corge, grault,
        garply, waldo, fred, plugh, xyzzy, thud {
    // Class body indented with 4 spaces.

Alternatively you may want to provide each implemented interface on its own line if it helps readability:

class provider implements
        // These lines are indented with 8 spaces to distinguish them visually from the class body.
        \core_privacy\local\request\core_userlist_provider {
    // Class body indented with 4 spaces.

Wrapping of the function signatures

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

Wrapping parameters of a function call

Normally, parameters will just fit on one line. If they eventually become too long to fit a single line or of it helps readability, indent with 4 spaces.

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

Wrapping arrays

There is nothing special and the general rules apply again. Indent the wrapped line with 4 spaces.

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

In many cases, the following style with each item on its own line will make the code more readable.

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

Note the last item has a trailing comma left there which allows to extend the list of items later with a cleaner diff. For the same reason, it is better not to align the assignment operators.

Wrapping arrays passed as function parameter

This is just an example of combining some of the examples above.

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

Line Termination

Use standard Unix text format. Lines must end only with a linefeed (LF). Linefeeds are represented as ordinal 10, or hexadecimal 0x0A.

Do not use carriage returns (CR) like old Macintosh computers (0x0D).

Do not use the carriage return/linefeed combination (CRLF) as Windows computers (0x0D, 0x0A).

Lines should not contain trailing spaces. In order to facilitate this convention, most editors can be configured to strip trailing spaces, such as upon a save operation. However, if you are editing an existing Moodle file and are planning to submit your changes for integration, please switch off that feature so that whitespace changes do not pollute the patch (other developers will have trouble viewing what you've done if every other line has been edited for whitespace).

Naming Conventions


Filenames should :

  • be whole english words
  • be as short as possible
  • use lowercase letters only
  • end in .php, .html, .js, .css or .xml


Class names should always be lower-case English words, separated by underscores:

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

Always use () when creating new instances even if constructor does not need any parameters.

$instance = new some_custom_class();

When you want an plain object of no particular class, for example when you are preparing some data to insert into the database with $DB->insert_record, you should use the PHP standard class stdClass. For example:

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

Before Moodle 2.0, we used to define a class object extending stdClass, and use new object(); This has now been deprecated. Please use stdClass instead.

Functions and Methods

Function names should be simple English lowercase words, and start with the Frankenstyle prefix and plugin name to avoid conflicts between plugins. Words should be separated by underscores.

Verbosity is encouraged: function names should be as illustrative as is practical to enhance understanding.

Note there is no space between the function name and the following (brackets).

function block_course_overview_get_overviews(array $courses) {
    // Actual function code goes here.

There is an exception for activity modules that still use only plugin name as the prefix for legacy reasons.

function forum_set_display_mode($mode = 0) {
    global $USER, $CFG;
    // Actual function code goes here.

Function Parameters

Parameters are always simple lowercase English words (sometimes more than one, like $initialvalue), and should always have sensible defaults if possible.

Use "null" as the default value instead of "false" for situations like this where a default value isn't needed.

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

However, if an optional parameter is boolean, and its logical default value should be true, or false, then using true or false is acceptable.


Variable names should always be easy-to-read, meaningful lower-case English words. If you really need more than one word then run them together, but keep them short as possible. Use plural names for arrays of objects. Use positive variables names always (allow, enable not prevent, disable).

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

Core global variables in Moodle are identified using uppercase variables (ie $CFG, $SESSION, $USER, $COURSE, $SITE, $PAGE, $DB and $THEME). Don't create any more!


Constants should always be in upper case, and always start with Frankenstyle prefix and plugin name (in case of activities the module name only for legacy reasons). They should have words separated by underscores.


Booleans and the null value

Use lower case for true, false and null.


Namespaces are not required for any new code and there is no requirement to move non-namespaced classes to namespaces. If namespaces are used - they must conform to these rules.

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.

The classname and filename for all namespaced classes must conform to the automatic class loading rules.

Use at most one namespace declaration per file.


<? // This is a file mod/porridge/classes/local/equipment/spoon.php
namespace mod_porridge\local\equipment;
class spoon {
    // Your code here.
// End of file.


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.


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


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.


$obj = new namespace\Another();

Do not use bracketed "namespace" blocks.


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.


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.


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.


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:


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 The classes in this namespace must either implement or use the API in some way.


  • "\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.



namespace mod_breakfast;                // Plugin's own namespace when not using nested namespaces (typical)
namespace mod_breakfast\local;          // Plugin's own namespace when using nested namespaces
namespace mod_breakfast\local\utils;    // Plugin's own namespace when using nested namespaces with further organisation
namespace mod_breakfast\event;          // Plugin's namespace to implement core API


namespace mymodule;                     // Violates the level1 rules - invalid component name
namespace mod_breakfast\myutilities;    // Violates the level2 rules - invalid core API name


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 ( = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
          JOIN {user} u ON = 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


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.


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


$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';


$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';


Numerically indexed arrays

When declaring indexed arrays with the array function, a trailing space must be added after each comma delimiter to improve readability:

$myarray = array(1, 2, 3, 'Stuff', 'Here');

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

$myarray = array(
        1, 2, 3, 'Stuff', 'Here',
        $a, $b, $c, 56.44, $d, 500);

Associative arrays

Use multiple lines if this helps readability. For example:

$myarray = array(
    'firstkey' => 'firstvalue',
    'secondkey' => 'secondvalue'


Class declarations

  • Classes must be named according to Moodle's naming conventions.
  • 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 in class files is permitted but discouraged. In such files, two blank lines must separate the class from any additional PHP code in the class file.
An example:
 * Documentation Block Here
class sample_class {
    // All contents of class
    // must be indented 4 spaces.

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;


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:
    case 2:


As above, uses spaces like this:

foreach ($objects as $key => $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.


$username = isset($user->username) ? $user->username : '';


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

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 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();

Documentation and comments

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


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:


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).
  • When multiple occurrences of a given "type" are used, it's highly recommended to document them as type[] instead of the simpler and less informative "array" alternative.
  • When multiple different types are possible, they must be separated by a vertical bar (pipe).
  • All primitives and keywords must be lowercase. The case of the complex types and classes must match the original.



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

 @copyright 2008 Kim Bloggs

These must be GPL v3+ and use this format:

 @license GNU GPL v3 or later

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

 @param type $name Description.

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.

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!


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

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

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

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 

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

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

 @see some_other_function()

If you want to refer the user to an external URL, use @link.

inline @link

Occasionally you might want to refer to something else inline within your text, say in a function description. For these cases you can use an inline @link (with an element name OR a URL) and it looks like this:

   * This function uses {@link get_string()} to obtain the currency names...
   * .....
@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.


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, to better control coverage within unit tests.
  • @dataProvider, within unit tests.
  • @expectedException[Code|Message|MessageRegExp], to define exception expectations, within unit tests. *)
  • @group, for easier collecting unit tests together, following the guidelines in the PHPUnit MoodleDocs.
  • @codingStandardsIgnoreLine, to allow next line to be skipped by the Codechecker (phpcs).
*) Please note that current best practice is to use
instead of the annotation syntax.


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)
// This file is part of Moodle -
// 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
// 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 <>.
 * 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 GNU GPL v3 or later


All classes must have a complete docblock like this:

 * Short description for class.
 * Long description for class (if any)...
 * @package    mod_mymodule
 * @copyright  2008 Kim Bloggs
 * @license GNU GPL v3 or later

(NOTE that classes that are fundamental to core APIs will also need a @category tag)

The exception are files containing only one class and nothing else. In that case the class is covered by the file docblock and adding an explicit class docblock is optional.


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

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


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;


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;


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}
 * 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.


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 = array();     // Initialize the empty array.
        $rates = $DB->get_records('forum_ratings', array('post' => $postid));
        // ... then process each rating in
        // turn.
        foreach ($rates as $rate) {
        // Do we need to tidy up?
        if (!empty($rates))
            // 42 more things happen here!


// Comment explaining this piece of code.


/*  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.

(The script .../lib/simpletest/todochecker.php in Moodle 2.0 will check this. Requires an admin login. This is a new requirement, see MDL-19772)

CVS keywords

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


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.

Any exception that is not caught will trigger an appropriate call to print_error, to report the problem to the user.

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:

base class for exceptions in Moodle. Use this when a more specific type is not appropriate.
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.
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


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

See also