Temporarily Disable Drupals Cache from within a Module

Are you using Drupal 6? Do you have caching turned on? Do you need it turned off for a small subset of special case scenarios? Here's how...

Drupals internal cache works just fine for most cases and is, in general, safe to just always have turned on. There are however times when it gets in the way with no clear way to bypass it. During normal operation Drupals internal cache is either just on or off. There are no options to tell it to not cache certain items or to disable caching for a specific module, in my case a custom module I have built. I discovered a work around for this where, in the module, you can disable the cache under virtually any condition you need.

The trick is to use hook_init and set $GLOBALS['conf']['cache'] = FALSE;.

Let's say that, for example, you have a module that defines a path of /my-awesome-module-display that you don't want cached. In your module just do something like:

function my_awesome_module_init() {
  if(preg_match("/my-awesome-module-display/", $_SERVER['REQUEST_URI'])) {
    $GLOBALS['conf']['cache'] = FALSE;
  }
}

That's all there is to it. This will temporarily disable the usage of Drupals internal cache for the given request/condition leaving the rest of the site still being cached. You can then, of course, implement any other special case scenario customizations in a similar fashion.

Implementing the aforementioned code in your module offers the most flexibility. In my case there are additional things that happen as well... but... if you just need to do not cache certain pages there is a module that does this as well giving you a simple admin interface to enter node paths to not cache called CacheExclude found at:

http://drupal.org/project/cacheexclude

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options