Drupal Coding Standards

The Drupal coding standards are a set of guidelines that describe how PHP code written for Drupal should be formatted. The standards describe things like how whitespace should be used, naming conventions to follow, how comments should be formatted, and how to properly indent code.

Following the coding standards has several benefits:

  • Code is easier to read and understand since developers spend less time deciphering the code and can focus on understanding what is going on.
  • Code is easier to maintain over time because all maintainers follow the same stylistic guidelines.
  • Non-compliant code, which is often indicative of low-quality or problematic coding, is easier to spot.
  • Collaboration is made easier because questions about code style and formatting are eliminated.

Programmers who follow the coding standards not only reap these benefits we've just described but also identify themselves as developers who care about details and who can work well in a collaborative environment.

A Primer on the Drupal Coding Standards

In this primer, we're going to take a high-level overview of the coding standards. If you need to inspect some of the finer details you can find the full text of the coding standards at the Drupal Association website.

The coding standards can be informally subdivided into four groupings:

Let's look at each in turn.

Basic Layout and Formatting

Coding standards that describe the basic layout and formatting define a specific style that enhances the readability of code for Drupal and minimizes stylistic disagreements between collaborating developers. Let's look at a block of properly formatted code and then review the guidelines that prescribe this specific format.

<?php
/**
 * Example of compliance with the Drupal coding standards.
 *
 * This short bit of code contains examples of php code
 * tags, comments, line length limits, indenting,
 * whitespace, URLs (example.com), and more.
 */

function imaginary_function($foo) {
  // Set $bar equal to $foo
  $bar = $foo;
  return $bar;
}

The code above is formatted to respect a variety of coding standards. Let's start by looking at how the comments in the code block are formatted.

  • Comments should begin with a forward slash and two asterisks followed by a line break.
  • Each subsequent new line within the comment block should be preceded by a space, an asterisk, and another space.
  • A summary sentence should be provided at the beginning of docblock style comments.
  • Inline comments are acceptable and should begin with two forward slashes.
  • All comments should be written using full sentences and proper grammar.

There are also some basic stylistic and document formatting rules in action in the code block above.

  • All comments must wrap at 80 characters or less.
  • Lines of code may exceed 80 characters if necessary, but it is preferable to wrap all lines at 80 characters.
  • The opening PHP tag must be the full tag, <?php, and not the abbreviated tag, <?.
  • Since this code contains just PHP code, the closing PHP tag, ?>, should be omitted. However, template files that contain a mix of HTML and PHP will use closing tags throughout the document as necessary.
  • Semicolons and curly braces that are optional in PHP are required when writing PHP for Drupal.
  • All example URLs should be to example.com.

The Drupal coding standard include very specific guidelines about the handling of whitespace. In the code block above we can see the following guidelines in action.

  • No trailing whitespace should be left at the end of any line.
  • Code should be properly indented using two spaces for each level of indentation and no tabs.
  • All files should end with a Unix style new line (\n) and not a Windows style new line (\r\n). This can be ensured by selecting Unix style line endings in your IDE or text editor.

Naming Conventions

There are naming conventions applying to all elements of Drupal code. Following these conventions allows developers to quickly identify the type of element they're dealing with when they encounter a new variable or function.

The official coding standards documentation provides a great deal of detail with regard to naming conventions. However, the most important factors to keep in mind can be summarized as follows:

  • Function names should be lowercase with underscores used to separate words. In addition, the grouping or module name should be used to prefix the function name.
  • Variable names should be lower case with words separated by underscores or written in lowerCamelCase. The key here is consistency. Use either underscores or lowerCamelCase, but don't mix the two.
  • Persistent variables should be lowercase with underscores used to separate words and the module name used as a prefix. This will ensure that other modules and the Drupal core do not tamper with these values.
  • Global variables are rarely set, but if they are defined they must begin with an underscore followed by the module name and another underscore and finally the name of the variable.
  • Constants, including the PHP constants TRUE, FALSE, and NULL, should be written in uppercase.
  • Class names should be UpperCamelCase while their methods and properties should be lowerCamelCase, and you should avoid using Drupal or Class in the names of classes or their methods and properties.
  • Finally, documentation file names should be all-caps and be saved with the .txt file extension, README.txt for example.

Below you can see examples of these naming conventions properly applied.

// A function for a fictional module named decaf.
function decaf_doesnt_count() { .. }

// A few properly named simple variables. However, note that
// you should not use both camelCase and underscores. Pick
// one or the other and be consistent.
$decaf = $boring;
$decafCoffee = NULL;
$decaf_coffee = 'Why bother?';

// A persistent variable.
$decaf_persistent_variable = 'sleepy';

// A class.
class DecafCoffee implements ImSoSleepy { .. }

Working with Variables

Variables are used to hold values such as booleans, arrays, and strings — and then to manipulate those values in a variety of ways. When working with variables and the tools like operators that are used to manipulate them, there are few coding standards to keep in mind.

  • Add an empty space before and after a binary operator used to compare two values or variables.
  • Do not add an empty whitespace between a unary operator and the value or variable it is acting on.
  • Values in an array should be separated by a comma and space.
  • Array values should be typed out on a single line unless they will exceed 80 characters. In which case they should be typed out in an indented vertical list.
  • When working with strings, single quotes are preferred (though not required). Use of double quotes is acceptable and recommended when used intentionally to allow variable interpolation or to avoid needing to escape single quotes within the string.
  • When concatenating strings, add a space before and after the dot operator.

The following code block demonstrates each of these standards in practice.

// Add space before and after a binary operator.
$coffee != $decaf;
if ($coffee < $regular) { .. }

// Do not add space between a unary operator and corresponding value.
function drink_coffee($focus) {
  $focus++;
  return $focus;
}
$sleepy = -$productivity;
$cups_to_alert = -3;

// How to format short arrays.
$coffeeBar = array('mugs', 'coffee maker', 'cream');

// How to format long arrays.
$makeCoffee = array(
  'cups_of_water' => 6,
  'tb_coffee' => 4,
  'basket_filter' => FALSE,
  'paper_filter' => TRUE,
  'brew_time' => '15 minutes',
  'auto_brew' => TRUE,
);

// Single quotes around strings are preferred.
$string = 'This is a string.';

// Double quotes are ok if they avoid the use of escape characters.
$string = "Sometimes it's good to use double quotes.";

// Double quotes can also be used to allow inline variable interpolation.
$string = "<h1>$title</h1>";

// Add a space before and after the dot when concatenating strings.
$fooBar = $foo . $bar;
$fooBar = 'foo' . 'bar';

Control Structures and Functions

Formatting control structures and functions properly makes it a lot easier to read the if statements, foreach statements, functions, and so forth that control the operation of your Drupal code. For this reason, the Drupal coding standards are pretty strict about how control structures should be presented.

First, let's look at how an if statement should be structured.

if ($foo > $bar) {
  // Action to take if $foo is greater than $bar.
}
elseif ($foo < $bar) {
  // Action to take if $foo is less than $bar.
}
else {
  // Action to take in the event that $foo is equal to $bar.
}

There are a few key points to notice in the code sample above:

  • Notice the use of whitespace between if and the condition, around the operator, and between the condition and the opening bracket.
  • Note that elseif rather than else if is used.
  • All new control structures should start on a new line (elseif is on a new line, not on the same line as the closing curly brace for the if statement).
  • The closing brace for a control structure should be on a line on its own.

Other types of control structures, such as switch, do-while, and foreach statements follow the same basic guidelines.

One exception to this format is when control structures are used within a template file, in that case, the format looks a bit different. Indentation still follows the same rules, but new lines aren't required and the following alternate control statement syntax can be used.

// Alternative if statement format for template files.
<?php if($foo > $bar): ?>
  <!--PHP and HTML to process if $foo is greater than $bar-->
<?php elseif($foo < $bar): ?>
  <!--PHP and HTML to use if $bar is greater than $foo-->
<?php else: ?>
  <!--PHP and HTML to use if $bar and $foo are equal-->
<?php endif; ?>

// Alternative foreach statement format for template files.
<?php foreach($fooBars as $fooBar): ?>
  <!--PHP and HTML to render for each $fooBar-->
<?php endforeach; ?>

The same standards that describe how control structures should be formatted come into play when dealing with functions. Here are two functions, one a declaration and the second a call, demonstrating how these principles apply to functions.

function foo_bar($bar, $foo = 1) { .. }
$fooBar = foo_bar($bar);

As you can see, the use of whitespace mirrors what we've covered elsewhere. In addition, note that we place $foo after $bar in the list of parameters. This is because $foo has a default value assigned to it. Function parameters with default values should appear at the end of the list of function parameters.

Classes are a special type of function and the standards that apply to them are similar to those that apply to functions. Here are two example of class constructor calls.

$foo = new FooBar();
$bar = new FooBar($baz, $qux);

As you can see, this matches the way functions are called but adds in the new constructor. Also, note that class constructor calls should include the parenthesis even if no arguments are being passed.

Resources

The guidelines prescribed by the Drupal coding standards aren't technically complex, but they are specific and thorough and they can be a bit tricky to get the hang of as a result. Thankfully, there are resources you can use to more fully internalize the Drupal coding standards and to check your code for violations of the standards.

  • Understanding the Drupal Coding Standards is a brief video that covers much of the same territory that we've covered in this primer. It provides an excellent and quick reinforcement of the material you've just read while working your way through this primer. Getting the same information in two different ways is an excellent way to master it quickly, so this video is worth taking a few minutes to watch.
  • Helper modules are Drupal modules and tools you can use to check your code for coding standard violations. Helper modules include popular and useful tools like Coder and Code Sniffer.

There's a lot more to writing code for Drupal than just following these coding standards and the Drupal Association website offers a variety of resources that can help you produce better work. While the full list of Drupal standards is worth consulting, the following selection should be consulted by every Drupal developer.

  • Object Oriented Code provides guidelines that apply when creating and working with classes.
  • CSS Standards is a collection of documents that describe coding standards, formatting guidelines, file organization, and other factors affecting CSS coding.
  • JavaScript Standards outline the coding standards that apply to code written in JavaScript and jQuery.
  • SQL Coding Conventions is a short but important document that outlines the guidelines to follow when working with MySQL.

Summary

The Drupal coding standards are comprehensive in their description of the way that code for Drupal should be formatted. Following the coding standards removes certain hindrances to collaboration and ensures that code written for Drupal is easier to understand and maintain. In this primer, we've introduced the most important coding standards that every Drupal developer must master. In addition, by using the resources provided within this primer, Drupal developers can deepen their knowledge of coding for Drupal and produce standard-compliant code with ease.