Best practices on Drupal 7

Best practices on Drupal 7

Even though I'm going to base on the official guide of best practices, here we will only present basic stuff.

Let's start:

How should I name my module?

As you wish! but always remember don't use reserved words or names that would be part of core or contrib modules. A bad name would be views_custom or node_baires. You better choose custom_views or baires_node.

This is a problem since someone who realizes that your module start with "views" could misunderstand and think this is an extension of views module.

Besides, the name of your module should be split by underscores, i.e.: my_module, and not myModule or mymodule, even when the last is better than the previous.

 

Where should I put my module?

For general rule, you should place your own module under /sites/all/modules/custom/mi_modulo, and contribute modules under /sites/all/modules/contrib/, leaving /modules/ for core modules.

If your module needs some extra files, like JavaScript or CSS, they should be included inside module package, i.e. my_module/js and/or my_module/css, then include them into your my_module.module file, by using drupal_add_js() and/or drupal_add_css() function, also is recommended for Drupal 7 to use hook_init() to perform those inclussions.

A little warning about something I find often: if your module's name is "favorites", it should have only functions related with that; a common mistake is put functionalities that are used in several places. To avoid it, a good strategy would be put all those stuff in a separated module named "customizations", or another meaningful name that reference us its content.

 

Where place my theme?

Like custom modules, custom themes should be placed in /sites/all/themes/mi_theme.

It is recommended using a theme based, we suggest mothership, it's pretty well structured, with a lot of configurations that will help later. It's focused in HTML5 but is not fully compliant. 

I'm currently using bootstrap theme

 

Basic tips:

a. Indent the code: Personally, I hate the code without indenting. When are indenting the code, it is more readable and understandable for all. According to the Drupal's good practices manual, the indent should be two blank spaces (not using tabs). I consider to this somewhat sparse and I use 4 spaces.

 

b. Short PHP code in the template files. In a template file should have a little logic (the logic should be on the modules). We must also use abbreviated conditional functions, example:

 

<?php if (is_null($var)):?>
hello word!
<?php else: ?>
other text
<?php endif; ?>

 

c. For SQL queries using the abstraction layer that Drupal provides.

 

d. Maximum use of the Drupal's functions. Use t() for the texts (help us with translations), Use l() for the links, and many other functions.

 

This is a long topic, surely there will be a sequel. I welcome your comments, questions, and contributions!

Tags