Best practices on Drupal 7

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

Lets 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 contib 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 realise 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 previus.

 

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 funtionalities that are uses in several places. To avoid it, a good strategy would be put all those stuff in a separated module named "customizations", or other 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 use a theme based, we suggest mothership, it's pretty well structure, with 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 indeting the code, it is more redeable and understandable for all. According to the Drupal's good practices manual, tje 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:

 

  1. <?php if (is_null($var)):?>
  2. hello word!
  3. <?php else: ?>
  4. other text
  5. <?php endif; ?>

 

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

 

d. Maximun use to the Drupal's functions. Use t() for the texts (help us with translations), Use l() for the links, and manu other functions.

 

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

Comments