Beginning Drupal Module Development or How I Wrote the Cacheflusher Module (Part 2)
Tags: DrupalDrupal ModulesDrupal Planet
This is the second part of Beginning Drupal Module development. If you missed the first part, you might want to review it before continuing with this tutorial.
Also thanks to drupaleasy for posting these on their site as well so they could be included in the Drupal Planet feed.
Creating Your .module File
Now that you have verified that your module's entry appears in the modules page in your development environment, it is time to add some information to your .module file.
This is where all of the work gets done and it contains all of the code for your module. Later, you can get fancy and use includes (.inc files) to help organize the module's function. For now though, you won't need any include files.
Open your favorite text editor again and on the first line add: <? php
This first line is needed to tell the web server that you are providing some php code. Don't close the tag though at the end with ?>
, this may add unneeded whitespace when your module runs.
The Drupal Framework Consists of Functions Called Hooks
Drupal modules are essentially a series of php functions that get executed by a trigger. This could be the user accessing a certain menu, saving a post, or a cron run. Your module integrates into Drupal by accessing Drupal specific triggers, that are referred to as hooks. Most modules have both hook functions as well as custom functions - which are usually there to encapsulate logic outside of a hook.
Documentation is Important
Throughout the api documentation and within Drupal core, you will find entries that use the format of hook_function_name
, if you examine other modules, you will also find that before these functions, there are code comments:
/**<br> * Implement hook_function_name()<br> */
Follow this format when you create your own module. This provides documentation to another developer about what is happening within your module and can give you some trouble-shooting tips if something goes wrong. The Drupal community likes documentation! Some module authors also prepend non-hook functions with an underscore character ("_") as a way to quickly identify them as well as ensure they don't coincidentally get used as a hook by some other module.