When contributing to an open source project as large as Drupal, it’s important to comply with the community’s coding standards for a variety of reasons:
- It helps maintain consistency in the code base.
- It reduces the time for submitted patches to get tested and accepted.
- It makes the code easier to debug and maintain.
- It typiclaly makes the code easier to read.
Learning about and apply the standards can take some time. Thankfully, members of the Drupal community have created the Coder module, which can be used to scan one’s code and provide detailed instructions on how to conform to the standard. This is an invaluable tool that should be used by any serious back end developer.
Still, the process of going in and applying these changes line by line can be time consuming. Thankfully, there are tools available that can automate a significant portion of that process. One example is the php-drupal bundle for Textmate. Simply select the snippet of code that you want to apply the Drupal coding standards to, go to the bundle commands list, and select “Coder format” (see below).
For example. The following code:
function hook_preprocess(&$variables, $hook)
{
static $hooks;
// Add contextual links to the variables, if the user has permission.
if(!useraccess('access contextual links')){return;}
if(isset($element) && isarray($element) && !empty($element['#contextuallinks'])) {
$variables['titlesuffix']['contextuallinks'] = contextuallinksview($element);
if (!empty($variables['titlesuffix']['contextuallinks'])) {$variables['classes_array'][] = 'contextual-links-region';}
}
}
Would get reformatted as follows:
function hookpreprocess(&$variables, $hook) {
static $hooks;
// Add contextual links to the variables, if the user has permission.
if (!useraccess('access contextual links')) {
return;
}
if (isset($element) && isarray($element) && !empty($element['#contextuallinks'])) {
$variables['titlesuffix']['contextuallinks'] = contextuallinksview($element);
if (!empty($variables['titlesuffix']['contextuallinks'])) {
$variables['classes_array'][] = 'contextual-links-region';
}
}
}
Note all the spacing issues have been resolved, newlines have been generated, etc. It should be noted that this bundle will not catch everything, but it will automatically adjust a significant portion of the most common issues. Any remaining issues can be found by using coder directly. Either way, both Coder module and the PHP-Drupal Textmate bundle are excellent tools and I highly recommend adding them to your own development environment.