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?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityHooks are called in order of
{system.weight}
. Lower weights come earlier in the calling process.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?
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.
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;
}
}