Magento – Have better Control Over Individual Block Cache
- Digital Engineering
Magento – Have better Control Over Individual Block Cache
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
1 2 3 4 |
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.
1 2 3 4 5 6 7 8 9 |
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.
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
1 2 3 4 5 6 7 8 9 10 |
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
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s