erikwebb's picture

Drupal Design Patterns: Creating your own hooks

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)

<?php
 
// will call all modules implementing hook_hook_name
 
module_invoke_all('hook_name');
?>

Example #2 (aggregate results)

<?php
  $result
= 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)

<?php
  $data
= 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)

<?php
 
// @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);
  }
?>

Tags: 

Comments

another tip

i got a little bit stuck when trying to implement a drupal_alter. so a tip for others reading this.
my hook: drupal_alter('graphapi_build_graph_data', $graph, $vars);

ist verry important that if you call it later you add & to the parameter you want to alter
function MYMODULE_graphapi_build_graph_data_alter(&$graph, $vars) ....

cheers

marco

Add new comment