23

Suppose there two modules, first_module and second_module which implement hook_user_login() hook.

When a user logs in, which function is called first?
How does Drupal decide the invocation order for hooks?

2 Answers 2

32

Hooks are called in order of

  1. Weight, which is defined per module in the database as {system.weight}. Lower weights come earlier in the calling process.
  2. Alphabetical, by module name.

By default, modules get assigned a weight of 0, so nearly all hooks in the system run in alphabetical order. Some modules will adjust this in their install hooks so they run earlier or later in the module_invoke_all function.

See also: Adjusting module weight: what are the risks and things to look out for?

4
  • 3
    Note in D7 there's hook_module_implements_alter().
    – Andy
    Aug 1, 2014 at 10:37
  • Is the alphabetic order 100% reliable?
    – donquixote
    Dec 20, 2019 at 14:14
  • 1
    @donquixote Yes and no. Weight will always come first. Alphabetical is done by the system as a sort (in Drupal 7, see module_implements() and module_list() ; forget where it is in Drupal 8). But, hook_module_implements_alter() can mess with those. In other words, when the alphabetical part happens, it is deterministic because core does the sort.
    – mpdonadio
    Dec 20, 2019 at 14:21
  • I checked the code, the sorting happens in the sql query when fetching the modules.
    – donquixote
    Dec 21, 2019 at 16:23
12

By default a modules weight defines its place in line to execute a hook_* function.

You may alter the default ordering of the implementing modules with hook_module_implements_alter. A small example can be found in further reading of this blog tutorial.

From that blog post an example implementation is:

function mymodule_module_implements_alter(&$module_list, $context){
 if($context === "node_insert"){
 $temp = $module_list['mymodule'];
 // Removing the mymodule key/value
 unset($module_list['mymodule']);
 // Adding the mymodule key value as the last member in the list
 $module_list['mymodule'] = $temp;
 }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.