Skip to Content

quick intro to drupal's cache system

Alaa's picture

Drupal modules can cache results of complex database queries in the cache table to reduce system load.

large drupal websites tend to have nodes and blocks with embedded php code, EGLUG has a bunch of php nodes but non of them involves complex queries.

however the iconbar block which is based on a flexinode type involves a relativly large number of queries, these queries get executed on every page view yet the content of the iconbar rarely changes.

so the eglug performance can be improved by caching the icon bar, admins please modify the block to look like this

<?php
$html = "";
$cid = "eglug:iconbar_block";
$cached = cache_get($cid);

if ($cached){
  $html = $cached->data;
} else {
  /* iconbar code here */
$html = /* put output here */;
cache_set($cid, $html, CACHE_PERMANENT);
}
print $html;
?>

so basically you select a unique identifier for the data you're about to cache or retireve from the cache table ($cid), cache_get attempts to load the data from cache, if it fails to find the data it returns 0.

if cache_get succeeds we simply print the cached data, if it fails we do our queries and generate the desired html, then store it in cache using cache_set before we print it.

cache_set takes an $expire argument, this can be a timestamp, CACHE_PERMANENT or CACHE_TEMPORARY, we chose CACHE_PERMANENT here because icon bar hardly ever changes, modules would usually take care of clearing the cache when needed, in eglug's case I guess admins will have to delete the 'eglug:iconbar_block' entry manually, or maybe create a php node that does that, all it takes is one single function call

<?php
cache_clear_all($cid);
?>

on manalaa.net for instance I have custom php blocks that list latest entires from Aggregator2 feeds, since aggregator2 runs every hour the cache $expire is set to time()+(60*60) to make it expire after an hour, highly volatile data should use CACHE_TEMPORARY which get's cleared on fairly regularly.

Comments

applied it.

Nice howto, I applied it to eglug's icons bar block. Thanks

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.


Dr. Radut | book