Drupal Coding Standards

“The Drupal Coding Standards apply to code within Drupal and its contributed modules…All new code should follow the current standards, regardless of (core) version. “

Drupal Coding Standards are a set of guidelines, in which Drupal expects you to follow when writing code. They were first introduced to improve readability, make code more maintainable and to improve consistency. This is especially helpful for anyone else who may read or work on the code in the future. Here are some of Drupal’s Coding Standards:

 

Indenting and Whitespace

Drupal state, you should indent with two spaces and no tabs. Spaces v Tabs is a popular debate that a lot of developers have and is usually down to preference but if the developer is using Drupal, they must now follow this standard of two spaces. Drupal also state, there should be no trailing Whitespace at the end. In general, when a file contains only PHP, we leave out the trailing closing tag of the PHP statement and leave a blank line at the end.

 

Operators

When writing operators in Drupal, you should leave a space before and after the operator to improve readability. So Operators should look like  $foo = $bar; rather than $foo=$bar;.

 

Line Length and Wrapping

In the Drupal Coding Standards, it states all lines of code should not be longer than 80 characters except lines that contain longer function names. It also states that conditions shouldn’t be wrapped into multiple lines.

 

Commenting

Drupal state, all comments should form proper sentences and should use US English spelling (e.g. color not colour). It also states there should be a space between the comment character (the * or the //) and the first letter of the sentence.

 

Naming Conventions

The standards state, that all functions should be named using lowercase, and words should be separated by using an underscore. Functions should also have the module or grouping name as a prefix to avoid name collisions between modules.

Variables should be named using lowercase and words should be separated by either using uppercase characters (e.g. $lowerCamelCase) or by using an underscore (e.g. $snake_case). You should be consistent, CamelCase and snake_case shouldn’t be mixed inside a file.