Magento Themes and Magento Extensions

Magento block caching

Share

Recently we were working on speeding up parts of client site which had usual problem of slow page loading caused by complicated configurable products. To solve the problem we were experimenting with extending core Magento caching capabilities.

Magento has built in predifined system of block output caching. Its block abstract has Zend_Cache caching capabilities that can be modified for your own needs. I’m showing here an example of caching whole product view block, however this is just a specific example of how things works, problems are different and requires different approach and solution.

I will start with some external reading and example itself. There is great article on Magento Wiki about this topic, along with category cache exampleon Magento forums.

With my Inchoo_BlockCaching.rar example module things should be little easier to understand.

Magento block caching depends of three things:
cache_lifetime => cache lifetime in seconds
cache_tags => cache type identifiers primarly used for deleting right cache at the right time
cache_key => cache identyfier

You can simply inject this data into construtor of any Magento block

1
2
3
4
5
6
7
8
protected function _construct()
{
$this->addData(array(
'cache_lifetime' => 3600,
'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG),
'cache_key' => $this->getProduct()->getId(),
));
}

or if you need some conditional approach like i did in this example define equivalent functions

1
2
3
public function getCacheKey(){}
public function getCacheLifetime(){}
public function getCacheTags(){}

because constructor approach isn’t enough in most scenarios.

There is a general misassumption about cache_lifetime. If you set it to false, Zend cache will get default value of 7200 seconds!! If you want infinite never expired cache set it to 9999999999, which is Zend_Cache maximum value, or something else big enough.

I believe that best way to activate this is to rewrite specific block with our own with caching enabled, like shown in example. You should always try to avoid modifying core files, even copying modified Mage classes to local, because things get really messy on updates.

Generated cached files can be found in usual subfolders of /var/cache folder. Two files are generated, first metadata file which contains serialized cache data and second one which is cached html output itself.
In my example:
mage—internal-metadatas—PRODUCT_INFO_STORE+ID_PRODUCT+ID
mage—PRODUCT_INFO_STORE+ID_PRODUCT+ID

Note that “Blocks HTML output” option needs to be enabled in Cache Management for this to work.

Many things in Magento can be cached in similar way and there are predefined mechanism waiting for you to use them. It’s possible that we’ll see more of this implemented in future Magento versions.

Leave a Reply

You must be logged in to post a comment.