How to cache a block in block_html cache type in Magento 2?
-
25-01-2021 - |
Question
I have a block file that does heavy data processing due to which my product page PHP rendering time increases above 2 seconds. I have disabled page_cache
in my Magento 2 system so i cannot use cacheable="true"
in my layout file that loads this block file with it's template. I am looking for a solution where i can cache this file code into block_html
cache type. Can anyone please tell me the solution on how i can implement this functionality.
My SampleClass
is below which is extending core Magento 2's \Magento\Catalog\Block\Product\View
class:
class SampleClass extends \Magento\Catalog\Block\Product\View
{
//rest of my code like __construct and other custom methods.
}
Solution
Finally got a solution for the above question.
I have used two methods getCacheLifetime()
and getCacheKeyInfo()
of the core Magento 2 template block file and overridden those two methods of the class: Magento\Framework\View\Element\AbstractBlock
.
The code looks like below:
//below code to set the life time of the cache
protected function getCacheLifetime()
{
return parent::getCacheLifetime() ?: 3600;
}
//below method to keep cache key unique for each product page.
public function getCacheKeyInfo()
{
$keyInfo = parent::getCacheKeyInfo();
$keyInfo[] = $this->getProduct()->getId(); // adding the product id to the cache key so that each cache built remains unique as per the product page.
return $keyInfo;
}
OTHER TIPS
Or you can just add di.xml on your frontend area as below:
<type name="MyBlock">
<arguments>
<argument name="data" xsi:type="array">
<item name="cache_lifetime" xsi:type="number">3600</item>
<item name="cache_key" xsi:type="string">UNQKEY</item> // Not needed unless same block name and multiple outputs based on pid or something
</argument>
</arguments>
</type>