
In the course of developing our site, we will frequently come across situations where various elements of the site need to be tweaked in PHP using Drupal's APIs. While a lot of theme-specific cases can be stored in template files, certain tweaks which are theme-agnostic require that we store them in a module to ensure that they are available to all themes.
This recipe covers the creation of a module to hold all these bits and pieces.
Create a folder inside sites/all
named modules
. This is where custom and contributed modules are usually housed.
The following list details the procedure involved in creating a module named mysite
to hold our theme-agnostic customizations and other odds and ends:
- Create a folder inside
sites/all/modules
namedmysite
where mysite refers to the name of our site. - Create a file named
mysite.info
within themysite
folder. - Edit this file and add the following code inside:
name = Mysite description = A module to hold odds and ends for mysite. core = 6.x
- Save the file.
- Create another file named
mysite.module
which will hold our odds and ends. - Save and exit the editor.
- Finally, enable the module via the module administration page at
admin/build/modules
(Home | Administer | Site building | Modules).
Just as with themes, modules require a .info
file which provides information to Drupal on compatibility, dependencies, and so on. Once Drupal ascertains that the module is compatible with the version installed, it loads the .module
file of the same name and processes it accordingly.
We can test if the module is working by adding a snippet such as the following:
<?php /** * Implementation of hook_init(). */ function mysite_init(){ // Display a message on every page load. drupal_set_message("Welcome to MySite!"); }
As the comment suggests, the preceding snippet will display a welcome message on every page load.
The Drupal community routinely comes up with modules to ease the pain of development.
There's a module available named Module builder which can be used to generate a skeleton of a general module. This can subsequently be populated as per our requirements. It is available at http://drupal.org/project/module_builder.