Last updated April 26, 2015. Created on July 14, 2014.
Edited by Speicus, bsandor, Scott Robertson, erikwebb. Log in to edit this page.

The Drupal 7 Hook Concept

Drupal’s hook system allows modules to interact with and alter data of other modules (or even Drupal core itself.) Read more...

To use a hook system you should create it (and call the implementations (invoking)) and implement it.

By reading this page you will have a solid understanding of hook concept and will see a few basic examples.

Creating a Drupal 7 hook (and calling their implementations)

Creating a hook and calling their implementations can be done by using one of the following functions (not all included): drupal_alter(), module_invoke_all(), module_invoke()

Implementing a Drupal 7 hook

To be able to call it you need to implement a drupal 7 hook.

If the module file is called example.module, then hook_help() as implemented by that module would be defined as example_help().

Drupal 7 Hook Types:

In common practice, there are two types of hooks that you want to create:

  1. Alter hooks:
    a common way to edit the contents of a particular object or variable by getting variables in the hook by reference, typically by using drupal_alter()
  2. Intercepting hooks:
    allowing external modules to perform actions during the execution, can not get variables by reference, typically by using module_invoke_all(), module_invoke()


Example #1 (Simple Invoking)

  // Calling all modules implementing 'hook_name':

Example #2 (Invoking a Particular one)

  // Calling a particular module's 'hook_name' implementation:
  module_invoke('module_name', 'name');
  // @note: module_name comes without '.module'

Example #3 (Collecting results in an array)

  $result = array();
  foreach (module_implements('hook_name') as $module) {
    // Calling all modules implementing hook_hook_name and
    // Returning results than pushing them into the $result array:
    $result[] = module_invoke($module, 'hook_name');

Example #4 (Altering data using drupal_alter())

  $data = array(
    'key1' => 'value1',
    'key2' => 'value2',
  // Calling all modules implementing hook_my_data_alter():
  drupal_alter('my_data', $data);
  // You should implement hook_my_data_alter() in all other modules in which you want to alter $data

Example #5 (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.