Drupal: Caching frequently used data

Often you will need to cache data in your projects to save valuable processing power and reduce hits on the database server.

Drupal provides caching functionality to you via the use of cache_get() and cache_set() functions.

/**
* Retrieves some sort of data.
*/
function module_get_rows($catid) {
  $key = "module_get_rows_$catid";
  $cache = cache_get($key);

  if ($cache) {
    return $cache->data;
  }

  $res = db_query("SELECT * FROM table_data WHERE catid = %d", $catid);
  $rows = array();

  while ($res && ($row = db_fetch_array($res))) {
    $rows[$row['catid'] = $row;
  }

  cache_set($key, $rows, 'cache', time() + 900);
  return $rows;
}

The example does the following:

  1. Create a cache key which is dependant on the $catid argument. This ensures that all the values are cached are depending on the category requested.
  2. Try to get an existing cache value using cache_get().
  3. If the cache is valid, return $cache->data.
  4. Otherwise, generate the cache data.
  5. Store the data using cache_set(). The cache will expire in the current time + 15 minutes, which is written as time() + 900 seconds.
  6. Return the data so the calling function can continue processing.
 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog