Best practices for coding in Drupal

Best practices for coding in Drupal

FFW Blog - illustration
FFW Marketing
Thought byFFW Marketing
Website Administrator
February 21, 2012

Members of the Drupal community have agreed that Drupal's codebase should adhere to a set of coding standards because standardization helps makes the code more readable. It also makes it easier for developers to understand and to edit each other's code.

Members of the Drupal community have agreed that Drupal's codebase should adhere to a set of coding standards because standardization helps makes the code more readable. It also makes it easier for developers to understand and to edit each other's code.

If you are just starting out developing in Drupal you will want to become familiar with these standards and use them consistently in your projects. To learn more about Drupal coding standards and best practices enroll in one of our Drupal Training classes in NYC such as PHP for Drupal or Drupal 7 Module Development.

Here are just a few key points we've highlighted.

Line Indentation

Drupal code uses 2 lines for indentation, with no tabs.

PHP Tags

Use opening PHP tags (<?php), but do not use closing PHP tags ( ?>).

Control Structures

Control structures control the flow of execution in a program and include: if, else, elseif, switch statements, for, foreach, while, and do-while. Control structures should have a single space between the control keyword and the opening parenthesis. Opening braces should be on the same line as the control keyword, whereas closing braces should have their own line.

if ($a == $b) {
do_this()
}
else {
do_that()
}

Function Declarations

Function declarations should not contain a space between the function name and the opening parenthesis.

function mymodule_function($a, $b) {
$do_somthing = $a + $b;
return $do_something;
}

Arrays

Arrays should be formatted with spaces separating each element and assignment operator. If the array spans more than 80 characters, each element in the array should be given its own line.

$car['colors'] = array(
'red' => TRUE,
'orange' => TRUE,
'yellow' => FALSE,
'purple' => FALSE,
);

Topics:
Technology

Read next:

Blog
FFW Blog - illustration

An Image is Worth a Thousand Words

Blog
Teaser image of Sitecore search indexes blog

Sitecore Search Performance: Tune-up Sitecore’s Search Indexes

Blog
Teaser of Drupal Europe blog

Join us at Drupal Europe this September

Blog
Teaser of Acquia Engage London blog

Acquia Engage - What a journey!