Block Cache and HTML Ouput
This is an old revision of the document!
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 :
- class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
- protected function _construct()
- {
- $this->addData(array(
- 'cache_lifetime' => 120,
- 'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG),
- ));
- }
- }
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 :
- class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
- protected function _construct()
- {
- $this->addData(array(
- 'cache_lifetime' => 120,
- 'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG),
- 'cache_key' => $this->getProduct()->getId(),
- ));
- }
- }
Consequences :
- The output will be different depends of your product id.
- Any product save will delete this cache
Example 3 |
Finally, we have :
- class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
- protected function _construct()
- {
- $this->addData(array(
- 'cache_lifetime' => 120,
- 'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG . "_" . $this->getProduct()->getId()),
- 'cache_key' => $this->getProduct()->getId(),
- ));
- }
- }
Consequences :
- The output will be different depending of your product id.
- Only a change of the specified product will delete the cache.


