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.

2 Answers 2


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;

Or you can just add di.xml on your frontend area as below:

<type name="MyBlock">
        <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
  • this solution is not working in magento 2.4.5 Commented Nov 8, 2022 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.