Moodle Coding Guidelines

Any collaborative project needs consistency and stability to stay strong.

These guidelines are to provide a goal for all Moodle code to strive to. It's true that some of the older existing code falls short in a few areas, but it will all be fixed eventually. All new code definitely must adhere to these standards as closely as possible.

General Rules

  1. All code files should use the .php extension.
  2. All template files should use the .html extension.
  3. All text files should use Unix-style text format (most text editors have this as an option).
  4. All php tags must be 'full' tags like <?php ?> ... not 'short' tags like <? ?>.
  5. All existing copyright notices must be retained. You can add your own if necessary.
  6. Each file should include the main config.php file.
  7. Each file should check that the user is authenticated correctly, using require_login() and isadmin(), isteacher(), iscreator() or isstudent().
  8. All access to databases should use the functions in lib/datalib.php whenever possible - this allows compatibility across a wide range of databases. You should find that almost anything is possible using these functions. Any other SQL statements should be: cross-platform; restricted to specific functions within your code (usally a lib.php file); and clearly marked.
  9. Don't create or use global variables except for the standard $CFG, $SESSION, $THEME and $USER.
  10. All variables should be initialised or at least tested for existence using isset() or empty() before they are used.
  11. All strings should be translatable - create new texts in the "lang/en" files and call them using get_string() or print_string().
  12. All help files should be translatable - create new texts in the "en/help" directory and call them using helpbutton().

 

Coding Style

I know it can be a little annoying to change your style if you're used to something else, but balance that annoyance against the annoyance of all the people trying later on to make sense of Moodle code with mixed styles. There are obviously many good points for and against any style that people use, but the current style just is, so please stick to it.

  1. Indenting should be consistently 4 spaces. Don't use tabs AT ALL.
  2. Variable names should always be easy-to-read, meaningful lowercase English words. If you really need more than one word then run them together, but keep them short as possible.

    GOOD: $quiz
    GOOD: $errorstring
    GOOD: $i (but only in little loops)

    BAD: $Quiz
    BAD: $aReallyLongVariableNameWithoutAGoodReason
    BAD: $error_string

  3. Constants should always be in upper case, and always start with the name of the module. They should have words separated by underscores.

    define("FORUM_MODE_FLATOLDEST", 1);

  4. Function names should be simple English words, and start with the name of the module to avoid conflicts between modules. Words should be separated by underscores. Parameters should always have sensible defaults if possible. Note there is no space between the function name and the following (brackets).

    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;
        }
    }

  5. Blocks must always be enclosed in curly braces (even if there is only one line). Moodle uses this style:

    if ($quiz->attempts) {
        if (
    $numattempts > $quiz->attempts) {
            
    error($strtoomanyattempts, "view.php?id=$cm->id");
        }
    }

  6. Strings should be defined using single quotes where possible, for increased speed.

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

  7. Comments should use two or three slashes and line up nicely with the code.

    function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {
    /// Return the mean rating of a post given to the current user by others.
    /// Scale is an array of possible ratings in the scale
    /// Ratings is an optional simple array of actual ratings (just integers)

        
    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

  8. Space should be used liberally - don't be afraid to spread things out a little to gain some clarity. Generally, there should be one space between brackets and normal statements, but no space between brackets and variables or functions:

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

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

 


Moodle Documentation

Version: $Id$