4

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.
}
asked Sep 12, 2018 at 12:29

2 Answers 2

7

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;
}
answered Sep 13, 2018 at 6:55
0

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>
answered Oct 1, 2019 at 9:35
1
  • this solution is not working in magento 2.4.5 Commented Nov 8, 2022 at 13:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.