Accueil / Blog / Métier / Archives / From hook_init() to hook_boot() : use "drush cc 'module list'" and not "drush cc all"

From hook_init() to hook_boot() : use "drush cc 'module list'" and not "drush cc all"

Par Benoit Bryon — publié 23/03/2011
If you add a hook_boot() implementation in a module, you need to rebuild the Drupal's module cache

If you add a hook_boot() implementation in a module, you need to rebuild the Drupal's module cache. "drush cc all" does not perform it, whereas "drush cc 'module list'" does.

Use case

In a Drupal-powered project, I had to perform an action at every page load. I first coded the action in an hook_init(). I saw that it worked on my own development  server and delivered it on a pre-production server.

/**
 * Implementation of hook_init().
 */
function some_custom_module_init() {
  do_something(); // The action doesn't matter
}

Wrong! Using hook_init() here was a mistake, because, as explained in the Drupal's documentation, hook_init() is not triggered for cached pages. So, once the cache had been enabled, the action was not triggered for most anonymous pages. A bug was filed.

Thus I converted the hook_init() into a hook_boot().

/**
 * Implementation of hook_boot().
 */
function some_custom_module_boot() {
  drupal_load('module', 'libraries'); // Manually load some requirements, because Drupal is in boostrap mode
  do_something(); // The action doesn't matter
}

The change had no effect. Why ?

Because the list of modules which implement hook_boot() is cached in some way. If you want details about this cache, read the code of bootstrap_invoke_all() and module_list().

So let's clear the cache! I use drush to perform such actions because then I can document it in an upgrade procedure, and even automate it in a script.

drush cc all

Still no effect. This is because "drush cc all"  does not actually clear all caches !

In fact, "drush cc all" invokes the drupal_flush_all_caches() function.

When I ran "drush cc", in interactive mode, it showed a "module list" option. This option invokes module_rebuild_cache(), which is what I needed in this use case.

So here is the solution:

drush cc "module list"

Problem solved! I documented it in the upgrade procedure.

Conclusion

I wonder why "drush cc all" does not actually clear all caches: is it a bug or a feature? I guess that "all" is related to "drupal_flush_all_caches", which makes sense in a way. Maybe I'd like a drush option to actually clear all caches listed in the interactive "drush cc" prompt.

To go deeper in drush and cache handling, notice that "drush cc" uses a drush hook, called "drush_cache_clear" to get the full list of "clear cache" operations. It means that you can create a custom drush command which implements "drush_cache_clear". Then "drush cc" will be able to invoke it! It may be pretty useful if your website handles some custom cache tables or a dedicated cache server like memcache.

ABONNEZ-VOUS À LA NEWSLETTER !