Best practices for coding in Drupal
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,
);