WordPress Stats Helper Plugin v0.2, Internal Options – Based Cache Details

Version 0.2 of the WordPress.com Stats Helper Plugin is out. Among the main changes:

  • internal, option-based, cache for data fetched from wordpress.com
  • added possibility to not display post views count (when using either as a function or as a widget)
  • capped post list to a maximum of 25 items

Andy expressed some serious concern when I first asked him to review this plugin: it was using wp_cache for data fetched from stats.wordpress.com. By default the cache is not enabled in wordpress (you have to manually set a variable in wp-config.php). He suggested I use the options to emulate a cache for my plugin. Here’s how I did it:

Cache structure

I’m using an option named opt_cache. This is an array which links every key to an entry. The entry itself is an array containing the actual value and the expiration time (expt):

$opt_cache = array('key' => array('value' => '', 'expt' => '');

Cache getter

First the data is searched in the wordpress cache. If not found, then it’s checked in the option-based cache. When data is found in the option-based cache it is also copied to the wordpress cache (since it’s faster).

// Cache getter
function opt_cache_get($key) {
	// Check wp_cache
	$result = wp_cache_get($key);
	if ($result) {
		return $result;
	}
	// Check option-based cache
	$opt_cache = get_option('opt_cache');
	if ($opt_cache) {
		$entry = $opt_cache[$key];
		if ($entry && $entry['expt']
				&& $entry['expt'] > time() ) {
			wp_cache_set($key, $entry['value'], '',
					$entry['expt'] - time());
			return $entry['value'];
		}
	}
	return false;
}

Cache setter

The data is set in both caches. If the option-based cache is not already created it will be created now, otherwise data is appended/updated to it.

// Cache setter
function opt_cache_set($key, $value, $expire = 500) {
	// Set wp_cache
	wp_cache_set($key, $value, '', $expire);
	// Set option-based cache
	$opt_cache = get_option('opt_cache');
	if (!$opt_cache) { $opt_cache = array(); }
	$opt_cache[$key] = array('value' => $value,
			'expt' => time() + $expire);
	update_option('opt_cache', $opt_cache);
}

Cache cleanup

This is only a matter of removing the option:

// Cache cleaner
function opt_cache_clear() {
	delete_option('opt_cache');
}

A good place to do that is on plugin disable:

// Watch for plugin deactivation
$plugin_filename= str_replace('\\', '/',
		preg_replace('/^.*wp-content[\\\\\/]plugins[\\\\\/]/',
				'', __FILE__));
add_action('deactivate_'.$plugin_filename, 'opt_cache_clear');

That’s about it!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>