# Moodle Coding Guidelines

Die Stabilität eines Programms wie Moodle hängt weesentlich davon ab, dass alle Entwickler des Programmcodes bestimmte Grundregeln einheitlich anwenden. Diese sind hier definert.

Dieser Text wird vorläufig nicht ins Deutsche übersetzt. Wir gehen davon aus, dass alle Anwender, die selber Programmteile für Moodle bearbeiten wollen so viel Englisch lesen und verstehen können dass sie diesen Text im Original verstehen.

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. If you must write SQL code then make sure it is: cross-platform; restricted to specific functions within your code (usually 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. Use plural names for arrays of objects.

   GOOD: $quiz
   GOOD: $errorstring
   GOOD: $assignments (for an array of objects)
   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;
   }

## Database structures

1. Every table must have an auto-incrementing id field (INT10) as primary index.
2. The main table containing instances of each module must have the same name as the module (eg widget) and contain the following minimum fields:
   - id - as described above
   - course - the id of the course that each instance belongs to
   - name - the full name of each instance of the module
3. Other tables associated with a module that contain information about 'things' should be named widget_things (note the plural).
4. Column names should be simple and short, following the same rules as for variable names.
5. Where possible, columns that contain a reference to the id field of another table (eg widget) should be called widgetid. (Note that this convention is newish and not followed in some older tables)
6. Boolean fields should be implemented as small integer fields (eg INT4) containing 0 or 1, to allow for later expansion of values if necessary.
7. Most tables should have a timemodified field (INT10) which is updated with a current timestamp obtained with the PHP time() function.

Moodle Documentation

Version: $Id: coding.html,v 1.5.2.3 2006/02/06 09:59:33 moodler Exp $