Block Cache and HTML Ouput

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

How to use HTML output 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.

This example only works for products... If you want to do the same thing for category, you should override the Model and add :

  1.     public function cleanCache()
  2.     {
  3.         Mage::app()->cleanCache('catalog_category_'.$this->getId());
  4.     }   
  5.    
  6.     protected function _beforeSave() {
  7.         $this->cleanCache();
  8.         return parent::_beforeSave();
  9.     }

Tips

If cache_lifetime is equal to false, it means that the cache will never expire.




 

Magento 2 GitHub Repository

Magento Job Board - Some sort of tag line goes here

Latest Posts| View all Jobs