Effective use of Magento Block Cache to improve page load speed

Caching

Is a mechanism to store data that is frequently accessed but rarely changed in order to have a faster response time. To make Magento performance better, we need to have caching, but lot of developers forgot or just don't care to add it in. Even Magento core doesn't support caching static CMS blocks.

For example, it is common to show featured products block in every eCommerce site. These products need to be loaded every time when the homepage is accessed. Homepage will receive lot of hits. Lot of time will be taken to execute same queries and re-drawing same block over and over. This will decrease the performance. Definitely we need to cache this block properly.

Magento block cache management is simple. It is written in the constructor of the Block.

          class Rrap_Featured_Block_View extends Mage_Core_Block_Template 
            {
                const FEATURED_TAG = "My Tag";

                protected function _construct() 
                {
                    $this->addData(array(
                        'cache_lifetime' => 3600,
                        'cache_tags' => array(self::FEATURED_TAG),
                        'cache_key' => 'SOME_KEY_THAT_HAS_TO_BE_UNIQUE'
                    ));
                }
            }
            
Magento block caching depends of three things:
  • cache_lifetime
  • cache_tags
  • cache_key

cache_lifetime

Cache lifetime is a period in seconds for the block will be cached. After the expiry of this period, first request that comes will not be served from cache, instead it will perform DB query, drawing the block and that result will be cached for the next period.

cache_tags

If we want to clear some of the blocks cached, we can refer to it via tag.
          $cache = Mage::app()->getCache();
          $cache->clean(array(Rrap_Featured_Block_View::FEATURED_TAG));
          

cache_key

If you have 2 stores in your Website with same featured product block in homepage. By giving cache key, we make sure that the same block is cached across all the stores.