Mikkel Høgh

Coding the web since 1999

11 Aug 2009

How to create and maintain your own cache table in Drupal

There’s a lot of good documentation for how to use the caching system already set up, in particular a very nice write up by Jeff Eaton that, even though it is written for Drupal 5, I find myself looking at rather often.

If you want to set up your own caching table, however, documentation is kinda scarce – I haven’t been able to find anything that covered it, but that may be due to my lack of Google skills.

In the end, I figured it out by reading the code of a lot of different modules, but I thought I’d take the time to do a write up of my own about how it can be accomplished.

First of all, you’ll need to set up your module. Once that is done, you’ll need these bits in your .install file to set up the new cache table. We’ll use the name “cachedemo” for this module, but it could really be anything.

<?php
/**
 * Implementation of hook_install().
 */
function cachedemo_install() {
  drupal_install_schema('cachedemo');
}

/**
 * Implementation of hook_uninstall().
 */
function cachedemo_uninstall() {
  drupal_uninstall_schema('cachedemo');
}

/**
 * Implementation of hook_schema().
 */
function cachedemo_schema() {
  $schema = array();

  $schema['cache_cachedemo'] = drupal_get_schema_unprocessed('system', 'cache');

  return $schema;
}

The trick here is using drupal_get_schema_unprocessed to make a 1-to-1 copy of the standard cache table. That will work fine in most cases, and saves you from typing out the entire schema.

The only other really required thing is to to implement hook_flush_caches, so our cache table can get flushed automatically:

<?php
/**
 * Implementation of hook_flush_caches().
 *
 * This tells Drupal's cache handling system the name of our caching
 * table, so expired items will be purged automatically and this table
 * also affected by the empty all caches function.
 */
function cachedemo_flush_caches() {
  return array('cache_cachedemo');
}

And that’s it. You’ll still have to do something with your new cache table – you can check Eaton’s write up mentioned in the start of this post out – most of it still applies to Drupal 6, although the argument order has changed in some places and it is no longer necessary to manually serialize and unserialize.

In the creation of this write up, I threw together a small demo module, just to check that the code I was posting was actually working. You can download it if you want.