Last updated July 25, 2014. Created on July 14, 2014.
Edited by Scott Robertson, erikwebb. Log in to edit this page.

Drupal’s hook system allows for modules to interact and alter the workings of other modules or even Drupal core itself. It is a very simple system that allows modules to even create their own very easily. In common practice, there are two types of hooks that you would want to create - alter hooks and intercepting hooks. Alter hooks provide a common way to edit the contents of a particular object or variable, typically using drupal_alter(). Intercepting hooks allow external modules to perform actions during the execution of another module.

Example #1 (simple invoking)

// will call all modules implementing hook_hook_name

Example #2 (aggregate results)

= array();
  foreach (
module_implements('hook_name') as $module) {
// will call all modules implementing hook_hook_name and
    // push the results onto the $result array
$result[] = module_invoke($module, 'hook_name');

Example #3 (altering data using drupal_alter)

= array(
'key1' => 'value1',
'key2' => 'value2',
// will call all modules implementing hook_my_data_alter
drupal_alter('my_data', $data);

Example #4 (passing by reference cannot use module_invoke)

// @see user_module_invoke()
foreach (module_implements('hook_name') as $module) {
$function = $module . '_hook_name';
// will call all modules implementing hook_hook_name
    // and can pass each argument as reference determined
    // by the function declaration
$function($arg1, $arg2);

Looking for support? Visit the forums, or join #drupal-support in IRC.


jnicola’s picture

Some clarification about example 3 would be useful. Specifically, what would a function calling that look like? Are parameters/variables passed by reference, or returned, etc etc.