We should not use a drupal_goto function in our module hooks!

Today one of my colleague nortmas had explained to the young developers one not obvious but extremely important point. In the begin of my career of Drupal developer I often did that kind of mistake.

I would like to share with us his message:

You should not put drupal_goto() into the hooks of our custom module!


Because our hook function is into the queue of the other functions that represent the same hook in the other contributed and custom modules. The order depends on the weight of the module and alphabetic order in the case of equal weights.

In the case if you will put drupal_goto in your hook function code, you will take away the ability to do necessary actions of the modules that located in the back of the hook order queue.

In any case you should avoid drupal_goto() function in your code because it indicated poor codding style like for example goto operator in classic C language.

Thank you, Dmitry for that helpful blog topic!

Blog tags: 


Probably wouldn't hurt to note the correct method-


The documentation [1] says: "Sends the user to a different Drupal page." How should I do this, without using drupal_goto?

[1] http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_goto/7

I would argue that not all hooks are equal in this case... hook_init() in a module with a very high weight will be much safer than hook_node_load(), for example. There are multiple contrib modules that leverage drupal_goto() (or equivalent) in hook_init() and hook_boot(). It is possible to set your module to have the highest weight of all currently installed modules in the .install file.

It is also possible to inspect what modules are implementing any hook you're worried about with module_implements().

To be fair, drupal_goto() isn't even defined by hook_boot() so, using the Drupal API, where are you suggesting that we *do* put drupal_goto()? An example of what you believe is right rather than just what is wrong would be helpful.

Which function would you recommend for redirection?

You have an event, and you have a hook as the way to react to that event. If you want to let other modules do their job create a new module with a weight like 10000000 and place your hook there.
Yes, this can be a mess with lots of modules competing for weight, but it is the drupal way of doing things.

Thanks for an awesome post!