Custom Cache in Magento

Every now and then, every developer has to deal with a huge amount of data that is slowing down their website and can’t be worked around. Fortunately, Magento has a caching system that allows us to cache our data in an easy and convenient way.

The model that we’re going to discuss in this article is Mage::getModel(‘core/cache’), which has 4 main methods:

php
1 2 3 4 save($value, $key, $tags = array(), $lifeTime=null); load($key); remove($key); clean($tags = array());

They are pretty much self-explanatory, but it’s good to specify what the $key and $tags variables represent. The $key variable is an identifier for the cached data and $tags aggregates the $keys. They allow us to either clear all related caches or choose the ones want we want to flush.

Since Magento already has a bunch of cache tags by default, we don’t always have to write our own modules (as long as assigning our custom cache to some of the default tags is reasonable) and we can jump right into action. Take a look at the example below:

php
1 2 3 4 5 6 7 8 9 10 11 12 13 $cacheId = 'example_id'; $cacheTag = 'block_html'; //check if our example_id cache contains any data - load() method will return false if cache is empty if (($data_to_be_cached = Mage::app()->getCache()->load($cacheId))) { //if cache was found then unserialize it and assign to our variable $data_to_be_cached = unserialize($data_to_be_cached); } else { //if not then normally assign data to the variable $data_to_be_cached = $exampleObject->exampleMethod(); //then serialize and save it Mage::app()->getCache()->save(serialize($data_to_be_cached), $cacheId, array($cacheTag)); }

Please note that we need to serialize the data so that can be stored as a string.

If we want to clear our example_id cache, we can either do it simply from the admin panel in Cache Storage Management and then refresh “Blocks HTML output” or do it programmatically using remove($cacheId) or clean(array($cacheTag)).

But what should we do if we want to add our own cache tag? Guess what, it’s just a matter of adding a couple of lines to the config.xml file of the module:

html
1 2 3 4 5 6 7 8 9 10 11 12 13 <global> ... <cache> <types> <ourcache translate="label,description" module="mycache"> <label>Custom Cache</label> <description>Description of our cache</description> <tags>CUSTOM_CACHE</tags> </ourcache> </types> </cache> ... </global>

As simple as that! Now, depending on your needs you can easily enable, disable or refresh your cache from Cache Storage Management.

This tutorial is based on the article by Andrei Danilchyk, which can be found under the following address: http://blog.belvg.com/using-default-magento-cache.html.