Magento Block Caching

Caching is very important in today’s world of ecommerce or any site where every millisecond count. The slower your site is the less conversion it is going to get because now a days everyone is so busy and they don’t have time and patience to wait for slower pages to load.

If you have the data which you know is always static or it changes rarely then the best way is that you should cache that data.

As in most of the modern web applications, we have cache management, simliarily we have it in magento as well, where you can add your data in cache and access it from cache instead of hitting the database.

This data could be anything on the page which you want to cache. Let’s go through some examples which can help understanding how cache works in Magento’s world.

Cache your blocks

protected function _construct()
{ $this->addData(array( 'cache_lifetime' => 3600, 'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG), 'cache_key' => $this->getProduct()->getId(), ));

You can add the above code in any block you want, that will cache the block’s output data in product cache for 3600 seconds i.e. 1 hour.

cache_lifetime – you can either specify number in seconds or false. If set to false, then cache will never expire.

cache_tags – cache tag is used to group the cache which means the same cache can be cleared or flushed at the same time. In the above example we are using product cache which mean this cache will be deleted as soon as any product is saved in admin. But if you want to make it unique and only get cleared the cache when specific product gets saved in admin then you can use the following code -:

protected function _construct()
{ $this->addData(array( 'cache_lifetime' => 3600, 'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG . '_' . $this->getProduct()->getId()), 'cache_key' => $this->getProduct()->getId(), ));

In the above example we have added $this->getProduct()->getId() with cache_tags and cache_key which makes the cache clearing and outputting unique. It will only clear cache when the particular product’s cache is cleared and display different output for each product on frontend.

cache_key – cache key is used to make the cache unique for each and every product. In both the above examples, we have product id as unique key which means for every product you have different version stored in cache. But if you know the block output is same across all the products then you don’t need to add the cache_key option at all. See the example below -:

protected function _construct()
{ $this->addData(array( 'cache_lifetime' => 3600, 'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG . '_' . $this->getProduct()->getId()), ));

Please note, you need to enable block html output cache from system->cache management section in admin to make the above code to work.

Similar Posts