The evil block cacher

There are two things that I have learned recently with Drupal

1) Caching of blocks can be enabled/disabled.  It is highly recommended to turn on this caching for production sites.  Your site can be heavily hammerered if you don't enable this.  I learned this firsthand. It would triple the time to execute a page.

2) Even if you enable the block cache, individual blocks that your custom module exposes can opt out of being cached (more on this later)

3) If you update the cache settings for a block contributed via a module, you will need to update the "blocks" table in your Drupal database to reflect your changes.  Any changes you make in your code will not be reflected until you fix the database record.  I found this out the hard way.  I updated my custom module to disable caching of my blocks, but it didn't work.  Then I found the post at http://drupal.org/node/235673 This describes the problem.  I fixed the problem by including a hook_update in my module, but you can just run some sql instead if that's what you want to do.

To customize the type of caching that you want a block to have, you have to set the "cache" element of the block's array to the type of cache you desire.  The following resource at http://api.drupal.org/api/drupal/modules--user--user.module/6/source was the real helper for me.   The user_block hook of the user.module as found below sets the 'cache' key value to the BLOCK_NO_CACHE argument.

One final note, as a reminder, if you disable caching of a block and that block has already been stored in the blocks table, you will have to update the table to disable caching.  Even removing/adding your block from a page region will not fix this.

 

/**
* Implementation of hook_block().
*/

function user_block($op = 'list', $delta = 0, $edit = array()) {
global $user;

if ($op == 'list') {
$blocks[0]['info'] = t('User login');
// Not worth caching.
$blocks[0]['cache'] = BLOCK_NO_CACHE;

$blocks[1]['info'] = t('Navigation');
// Menu blocks can't be cached because each menu item can have
// a custom access callback. menu.inc manages its own caching.
$blocks[1]['cache'] = BLOCK_NO_CACHE;

$blocks[2]['info'] = t('Who\'s new');

// Too dynamic to cache.
$blocks[3]['info'] = t('Who\'s online');
$blocks[3]['cache'] = BLOCK_NO_CACHE;
return $blocks;
}

Comments

Post new comment

  • 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