Making use of Magento's cache

Popular open source e-commerce solution Magento can be quite slow, but there are ways of improving its performance. Caching is one very effective way and Magento supports various caching backends out of the box, including Memcached. If you write your own Magento extensions, be they plugins or templates, you might benefit from using the cache for things that might otherwise tie up a lot of resources to recompute. This is quite easy to do, but information on caching is surprisingly rare. So how do you do it?

Using a cache is quite simple. First, you check whether the data you need is already in the cache. If it is, then you can simply use it and be done. If not, you will need to do whatever you need to do to compute or construct that data. Then, place it in the cache where it will remain for later use. Bear in mind that in order to be safe, the data should be stored in string form and needs to be serialised upon placement in the cache, deserialised upon retrieval. Here's some sample code, making use of Magento's built-in cache, regardless of the configured backend:

//Get a handle to interface with Magento's caching backend
$cache Mage::app ()->getCacheInstance ();
//Try to load the item from the cache
$temp $cache->load ('item-identifier');
if (
$temp !== false)
//The item was loaded from the cache (as a string), so restore the actual item object
$item unserialize ($temp);
} else {
//The item was not in the cache so, do whatever it is you need to do to build it here:
$item /* insert loads of stuff here */;

//Item has been rebuilt, so store a serialized version of it in the cache
$cache->save (serialize ($item), 'item-identifier', array (), 3600);

The string 'item-identifier' is used as a key to store/retrieve your cached data; think of it as a name for the slot you're using in the cache. Choose a unique on for each thing you're placing in the cache. The empty array() can be used to specify a set of tags, but since not every caching backend supports tags, I've left this empty. And finally, the 3600 is the number of seconds to keep the item cache. After 1 hour, the cached data is marked expired. Note, however, that the caching backend may chose to evict the data from the cache much earlier than that, such as when it runs out of memory.

There are only two hard things in Computer Science: cache invalidation and naming things — Phil Karlton

Be sensible about chosing a time during which your data should be cached. Make your choice based on how often your data is accessed and how dynamic it is. If your timeout is too short, you lose the benefits of caching and you end up recalculating every time the data is accessed. If your timeout is too long and your data too dynamic, you may get stale data.


No comments, yet...

Post a comment