A Developer’s Guide to using the Magento Cache
As you’ll undoubtedly know Magento supports caching. Most of us will find that one out after 20 minutes of refreshing, checking our code, refreshing, only to find that caching was still enabled! But as a developer, how can we make use of this, obviously, in-built feature?
All of the caching functions are available through Mage_Core_Model_Cache which we’ll call as a singleton:
$cache = Mage::getSingleton('core/cache');
This gives us access to whatever caching mechanism we have set up be it apc, memcached, xcache, or just a simple file. Instructions for setting up memcached are shipped with Magento in the app/etc/local.xml.additional file.
The $cache object has four methods we are interested in:
save($value, $key, $tags = array(), $lifeTime=null)load($key)remove($key)clean($tags = array()
These methods will allow us to manipulate the values that we have in the cache cleanly and with ease.
Storing Values
We'll start with storing a value.
$cache->save(date("r"), "nick_date", array("nicks_cache"), 10); $cache->save("hello world - " . time(), "nick_helloworld", array("nicks_cache"), 60*60);
With the above example I have instructed the cache to store the value of the current date with the key nick_date. We'll be able to refer to this date using the key at a later date. I've also stored the phrase hello world - 601992000 (for the given timestamp) with the key nick_helloworld.
We'll ignore the tag nicks_cache for the time being, but you will notice an integer lifeTime value associated with both cache entries. This is the amount of time, in seconds, that the value will exist in cache before being deleted. By setting this value to null, or omitting the argument, the value will remain in cache until removed.
Retrieving Values
To fetch the value of a key from cache, we simply use:
$cache->load("nick_date");
If the value does not exist in cache then false will be returned.
Removing Values
To remove individual values from the cache, we use:
$cache->remove("nick_date");
You'll notice that I've also applied the nicks_cache tag to the cache entries I initially stored. By applying a tag to a set of values I am able to refer to them all at a later for mass removal. We do this by:
$cache->flush("nicks_cache");
This will delete all cache entries with the tag nicks_cache.
Thanks for this Nick, would be really useful if i could get it working. is this a new thing in 1.4? i just get an error on 1.3
Impossible to tell without knowing the error.
Brilliant! Thanks. This is quite useful while fetching data from external URL which does not change too often.