Block Cache and HTML Ouput

Last modified by Laurent Bourrel on Fri, June 25, 2010 09:22
Source|Old Revisions  

This is an old revision of the document!


How to use HTML ouput cache in Magento

The output html of a block can be saved in the Magento cache.

For the moment, there’s nearly no blocks saved in the default Magento store, except the frontend and admin headers.

Example 1

The cache management has to be written in the constructor of the Block :

  1. class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
  2.  
  3.     protected function _construct()
  4.     {
  5.         $this->addData(array(
  6.             'cache_lifetime'    => 120,
  7.             'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG),
  8.         ));
  9.     }   
  10.  
  11. }

In this exemple, we have a time to live of 120 seconds. The output code will be saved in cache until the “Product” cache will be deleted.

Consequences :

  • Any product save will delete this cache
  • This code is OK if and only if the output does not depend of a specific product. If you are doing so for the product view, all your products will have the same output !

Example 2

Then, let’s consider the following example :

  1. class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
  2.  
  3.     protected function _construct()
  4.     {
  5.         $this->addData(array(
  6.             'cache_lifetime'    => 120,
  7.             'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG),
  8.             'cache_key'            => $this->getProduct()->getId(),
  9.         ));
  10.     }   
  11.  
  12. }

Consequences :

  • The output will be different depends of your product id.
  • Any product save will delete this cache

Example 3

Finally, we have :

  1. class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
  2.  
  3.     protected function _construct()
  4.     {
  5.         $this->addData(array(
  6.             'cache_lifetime'    => 120,
  7.             'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG . "_" . $this->getProduct()->getId()),
  8.             'cache_key'            => $this->getProduct()->getId(),
  9.         ));
  10.     }
  11.    
  12. }

Consequences :

  • The output will be different depending of your product id.
  • Only a change of the specified product will delete the cache.



 

Magento 2 GitHub Repository

Magento Job Board - Some sort of tag line goes here

Latest Posts| View all Jobs