Coding standards

Note: The Drupal Coding Standards applies to code that is to become a part of Drupal. This document is based on the PEAR Coding standards.

Indenting

Use an indent of 2 spaces, with no tabs. No trailing whitespace.

Control Structures

These include if, for, while, switch, etc. Here is an example if statement, since it is the most complicated of them:

if (condition1 || condition2) {
  action1;
}
elseif (condition3 && condition4) {
  action2;
}
else {
  defaultaction;
}

Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.

You are strongly encouraged to always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added.

For switch statements:

switch (condition) {
  case 1:
    action1;
    break;

  case 2:
    action2;
    break;

  default:
    defaultaction;
}

Function Calls

Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example:

$var = foo($bar, $baz, $quux);

As displayed above, there should be one space on either side of an equals sign used to assign the return value of a function to a variable. In the case of a block of related assignments, more space may be inserted to promote readability:

$short         = foo($bar);
$long_variable = foo($baz);

Function Declarations

function funstuff_system($field) {
  $system["description"] = t("This module inserts funny text into posts randomly.");
  return $system[$field];
}

Arguments with default values go at the end of the argument list. Always attempt to return a meaningful value from a function if one is appropriate.

Arrays

Arrays should be formatted with a space separating each element and assignment operator, if applicable:

$some_array = array('hello', 'world', 'foo' => 'bar');

Note that if the line spans longer than 80 characters (often the case with form and menu declarations), each element should be broken into its own line, and indented one level:

$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#size' => 60,
  '#maxlength' => 128,
  '#description' => t('The title of your node.'),
);

Note the comma at the end of the last array element; This is not a typo! It helps prevent parsing errors if another element is placed at the end of the list later.

Comments

Inline documentation for source files should follow the Doxygen formatting conventions.

Non-documentation comments are strongly encouraged. A general rule of thumb is that if you look at a section of code and think "Wow, I don't want to try and describe that", you need to comment it before you forget how it works.

Non-documentation comments should use capitalized sentences with punctuation. All caps are used in comments only when referencing constants, e.g., TRUE. Comments should be on a separate line immediately before the code line or block they reference. For example:

// Unselect all other contact categories.
db_query('UPDATE {contact} SET selected = 0');

If each line of a list needs a separate comment, the comments may be given on the same line and may be formatted to a uniform indent for readability.

C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is discouraged.

Including Code

Anywhere you are unconditionally including a class file, use require_once(). Anywhere you are conditionally including a class file (for example, factory methods), use include_once(). Either of these will ensure that class files are included only once. They share the same file list, so you don't need to worry about mixing them - a file included with require_once() will not be included again by include_once().

Note: include_once() and require_once() are statements, not functions. You don't need parentheses around the filename to be included.

PHP Code Tags

Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for Drupal compliance and is also the most portable way to include PHP code on differing operating systems and setups.

Note that as of Drupal 4.7, the ?> at the end of code files (modules, includes, etc.) is purposely omitted. The full discussion that led to this decision is available from the no ?> needed at the end of modules discussion on the drupal-devel mailing list, but can be summarized as:

  • Removing it eliminates the possibility for unwanted whitespace at the end of files which can cause "header already sent" errors, XHTML/XML validation issues, and other problems.
  • The closing delimiter at the end of a file is optional.
  • PHP.net itself removes the closing delimiter from the end of its files (example: prepend.inc), so this can be seen as a "best practice."

Header Comment Blocks

All source code files in the core Drupal distribution should contain the following comment block as the header:

<?php
// $Id$

This tag will be expanded by the CVS to contain useful information

<?php
// $Id: CODING_STANDARDS.html,v 1.14 2008/02/19 03:36:41 ax Exp $

Using CVS

Include the Id CVS keyword in each file. As each file is edited, add this tag if it's not yet present (or replace existing forms such as "Last Modified:", etc.).

The rest of this section assumes that you have basic knowledge about CVS tags and branches.

CVS tags are used to label which revisions of the files in your package belong to a given release. Below is a list of the required CVS tags:

DRUPAL-X-Y
(required) Used for tagging a release. If you don't use it, there's no way to go back and retrieve your package from the CVS server in the state it was in at the time of the release.

Example URLs

Use "example.com" for all example URLs, per RFC 2606.

Naming Conventions

Functions and Methods

Functions and methods should be named using lowercase and words should be separated with an underscore. Functions should in addition have the grouping/module name as a prefix, to avoid name collisions between modules.

Private class members (meaning class members that are intended to be used only from within the same class in which they are declared; PHP 4 does not support truly-enforceable private namespaces) are preceded by a single underscore. For example:

_node_get()

$this->_status

Constants

Constants should always be all-uppercase, with underscores to separate words. This includes pre-defined PHP constants like TRUE, FALSE, and NULL. Prefix module-defined constant names with the uppercased name of the module they are a part of.

Global Variables

If you need to define global variables, their name should start with a single underscore followed by the module/theme name and another underscore.

Class Names

Though classes are rarely used in Drupal, their name should use "studlyCaps." For example:

$type = new stdClass();
  

Filenames

All documentation files should have the filename extension ".txt" to make viewing them on Windows systems easier. Also, the filenames for such files should be all-caps (e.g. README.txt instead of readme.txt) while the extension itself is all-lowercase (i.e. txt instead of TXT).

Examples: README.txt, INSTALL.txt, TODO.txt, CHANGELOG.txt etc.

Helper Script

There is a helper command line script included with Drupal to check your code for style compliance. The code-style.pl file is located in the /scripts. To use the script just give your file as an argument when you execute the script (make sure the script is executable):

./code-style.pl path/to/file/example.module

This will output a list of suggestions for where to improve your code. You will need to make the actual changes to the code yourself.

Helper Module

There is a contrib module for assisting with code review. To use this module, install the coder module, click on the "Code Review" link in your navigation menu, scroll down to "Select Specific Modules", select the module you wish to review, and click the "Submit" button.

Files should be 'Unix' (not MS-DOS) format?

dman - January 6, 2006 - 03:33

I don't see it mentioned explicitly here (I know it's basically just assumed in the Unix world) but it should probably be stated that PHP source is expected to use just \n not the old \r\n that some (Windows) text editors may default to.

PHP, HTML, XML and the rest seem to get along just fine either way, but it can cause really hard-to-see errors in obscure places and may annoy most maintainers.

See your text editor preferences (Document Classes/File Formats) to set *.php and *.module files to 'Unix'

.dan.

http://www.coders.co.nz/

It would be desirable to create a section about functions

trunks - October 9, 2007 - 12:41

From C Coding Standards:

Functions should be short and sweet. If a function won't fit on a single screen, it's probably too long. Don't be afraid to break functions down into smaller helper functions. If they are static to the module an optimizing compiler can inline them again, if necessary. Helper functions can also be reused by other functions.

However, sometimes it is hard to break things down. Since functions don't nest, variables have to be communicated through function arguments or global variables. Don't create huge interfaces to enable a decomposition that is just not meant to be.

Module names (and hook declarations) *must* be lowercase

gpk - May 26, 2008 - 16:55

Functions and methods should be named using lowercase and words should be separated with an underscore. Functions should in addition have the grouping/module name as a prefix, to avoid name collisions between modules.

This implies that module names should also be lowercase. However in fact module/function names *must* be in uppercase to guarantee everything works (see http://drupal.org/node/200628), but Drupal doesn't actually enforce this requirement.

gpk
----
www.alexoria.co.uk

Uppercase?

xurizaemon - June 3, 2008 - 02:16

@gpk: Uppercase, ugh! That forum thread you link to suggests to me that function names and module names must be lowercase.

Was that just a typo in your post perhaps?

Update: Seems it must be, looking at the post in that thread where you say lowercase not upper. Leaving this comment to clarify for other readers.

Ooops

gpk - June 3, 2008 - 06:24

Thanks for spotting my deliberate mistake not :P

gpk
----
www.alexoria.co.uk

Including files + Coder Format

sun - June 4, 2008 - 03:03

1) #235459: add leading period+slash to views_include() sounds sane and should be added.
2) Coder module ships with Coder Format that should be added to the Helper Script[s] section. It is included in Coder's releases since 5.x, but has been vastly improved for 6.x (Thanks ezyang!). It should be noted however that Coder Format actually re-formats (changes) all PHP files, so they should ideally be fresh CVS checkouts and all changes need to be reviewed afterwards.

Daniel F. Kudwien
unleashed mind

API module depends on these standards

seanburlington - June 29, 2008 - 23:21

It's worth noting that the API module (responsible for api.drupal.org) depends upon adherence to the above standards.

function foo($bar){

will not be documented properly (there's a missing space before the opening brace)

Sean Burlington
www.practicalweb.co.uk
London

A 404 Error

TechSteve - July 10, 2008 - 23:14

Just found one 404 error:
The link of 'no ?> needed at the end of modules' under section 'PHP Code Tags' is dangling.

The standards are pretty clear and helpful for a newbie to Drupal, Thanks!

Steve

 
 

Drupal is a registered trademark of Dries Buytaert.