Home/Magento – Have better Control Over Individual Block Cache

Magento – Have better Control Over Individual Block Cache

Published On: 19 December 2013.By .
  • Product & platform Engineering

Magento provides Block cache in backend but what if we need more granular control over a particular block caching?

For e.g.:-
1. I do not want to cache my catalog page and want to keep HTML block caching enabled.
2. I want to control block cache conditionally.

Solution:-
To disable the block caching we have to comment the code from where magento add the cache data  or fetch the cache key of that particular block.Normally Block file has a constructor from where magento add the cache data or has a function to get the block cache key.

Below is the solution for catalog page cache:

To disable the catalog page cache, open

app/code/core/Mage/Catalog/Block/Product/List.php or app/code/local/ Mage/Catalog/Block/Product/List.php (if you have customize the code).

Find getCacheKey() function and comment the code. So your code should be like this

public function getCacheKey()
{
//  return $this->getRequest()->getRequestUri();
}

Other way of block caching in Magento is from constructor of the block file. You will find below code for block caching.

protected function _construct()
{
    $this->addData(
             array('cache_lifetime'=> false,
                   'cache_tags'=>array(
                       Mage_Catalog_Model_Category::CACHE_TAG,
                      Mage_Core_Model_Store_Group::CACHE_TAG),
             ));
}

So just comment this line and that block will not be cache now.

magento tips

Magento Tips- Aurigait.com

Now to have more granular control on block caching, you have to play around with block caching key.

For e.g.- I Customized the catalog page in one of my project to filter the products according to the gender of the Customer.But when I manually changed the gender to see other gender’s product,It still displayed the current gender’s product due to block caching.So I added gender in the cache key and it solve my problem.

So in my case my solution was

public function getCacheKey()
{
    $gender=$_SESSION['selected_gender'];
    if($gender=='men')
      return $this->getRequest()->getRequestUri()."?gender=men";
    elseif($gender=='women')
      return $this->getRequest()->getRequestUri()."?gender=women";
    else
      return $this->getRequest()->getRequestUri();
}

In this way you can have better control over individual block caching.

Related content

We Love Conversations

Say Hello
Go to Top