Magento Expert Forum - Improve your Magento experience

Results 1 to 3 of 3

Adding Cache Support to Magento Blocks

  1. #1
    Junior Member sgdev's Avatar
    Join Date
    Apr 2013
    Posts
    11
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Adding Cache Support to Magento Blocks

    Caching is an essential feature of Magento for maintaining performance. Magento provides a caching mechanism for Layout, Blocks, Collection Data, and Configurations. Normally layout updates, configuration data, etc. remain the same each time a page is loaded. Fetching layout updates from multiple files or loading and merging configuration data from XML files and the database cost significant amounts of execution time. Caching provides a mechanism to prepare and store all this data conveniently so it can quickly be retrieved on page loads to save execution time.

    In this tutorial, we will cover how you can prepare your custom blocks for block caching.

    In block caching, Magento stores the HTML output of the blocks into its cache and subsequently loads the contents directly from it. By default, Magento uses block cache only for the header, footer and top navigation, as their contents is not frequently changed. However, using caching for other blocks is also possible.

    Cache Lifetime

    The simplest way of enabling cache for a particular block is to set cache_lifetime data. This can be done through layout XML:

    HTML Code:
    <block type="mb_example/cached" name="magebase.example">
        <action method="setCacheLifetime">
            <lifetime>3600</lifetime> <!-- Cache Lifetime of 1 hour -->
        </action>
    </block>
    Or it can also be defined in the _construct() method of a block class:

    PHP Code:
    <?php
    class Magebase_Example_Block_Cached extends Mage_Core_Block_Abstract
    {
        protected function 
    _construct()
        {
            
    $this->setCacheLifetime(3600);
        }
        ...
    }
    Cache Lifetime is time specified in seconds, which defines the expiration time of the cache. In our example we have defined the cache lifetime as 3600 seconds i.e. 1 hour. So our cache would expire after 1 hour, and then re-generated. If cache lifetime is passed as false, the cache will never expire.

    Cache Tags

    Additionally to the cache lifetime, we can specify cache tags. Tags are useful to programmatically identify particular cache types. In our example, we will add two cache tags: store and cms_block

    PHP Code:
    <?php
    class Magebase_Example_Block_Cached extends Mage_Core_Block_Abstract
    {
        protected function 
    _construct()
        {
            
    $this->addData(array(
                
    'cache_lifetime' => 3600,
                
    'cache_tags'        => array(Mage_Core_Model_Store::CACHE_TAGMage_Cms_Model_Block::CACHE_TAG)
            ));
        }
        ...
    }
    Cache Keys

    Probably the most important part of preparing your blocks for caching is specifying the cache key. The cache key uniquely identifies each cache item. If a cache key is not specified, Magento uses the block’s name in the layout as the cache key. However, it is a good practice to define a custom cache key when adding cache support to the block.

    To define a cache key, we can either add a static value of cache_key through the layout XML similarly to the cache lifetime in the above example or add a data key called cache_key through the _construct() method. A unique static string value is sufficient to define a cache key, however, we should consider a scenario when the block has different output for different stores, themes, etc…

    For example, a block can have different HTML output for different themes. If we define a static cache key, it will be the same for any theme. So our cache will store the first rendered output, regardless of the theme. When a theme is changed or used by another website in the same Magento install, the same HTML would be returned from cache. That’s why it’s a good idea to have the cache key depended on the theme, package, store etc.

    To create a unique cache key, we should override the method getCacheKeyInfo() in our block class and return an array of cache key parts:

    PHP Code:
    public function getCacheKeyInfo()
    {
        return array(
            
    'EXAMPLE_BLOCK',
            
    Mage::app()->getStore()->getId(),
            (int)
    Mage::app()->getStore()->isCurrentlySecure(),
            
    Mage::getDesign()->getPackageName(),
            
    Mage::getDesign()->getTheme('template')
        );

    Here, the method returns an array. The first element 'EXAMPLE_BLOCK' is our unique identifier. The second element is the current store id. The third element is 1 if current URL is secure (https://) or 0 if URL is not secure. The fourth element is the theme package name. The fifth element is the theme name for rendering templates. The cache key for the block will be generated using all these array elements.

    In our example, the cache key will automatically be changed when:

    1. Customer browse to different store
    2. URL is changed from secure (https://) to unsecure (http://) or vice versa
    3. Theme package is changed by administrator
    4. Theme for templates is changed by administrator


    As you can see, the array elements for the cache key should be chosen according to the block’s output for different factors. On some site you may be allowing for a currency or language switcher, or both, so in those cases you will need to add more key elements to create a unique cache key specific to the selected currency and/or language, and so on.

    Conclusion

    We hope you found this short tutorial useful. We recommend adding block cache support for your blocks, especially if you’re creating custom home page blocks or widgets. It will improve the response of the site considerably. The trick is to be mindful about how to create the unique cache key to avoid strange display behaviour in some scenarios.

    View more threads in the same category:


  2. #2
    Junior Member rocker's Avatar
    Join Date
    Mar 2013
    Posts
    105
    Thanks
    3
    Thanked 11 Times in 9 Posts

    Default

    Very good tips, thanks guy

  3. #3
    Junior Member
    Join Date
    May 2014
    Location
    India
    Posts
    28
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default

    I usually get issues with cache lifetime and this post was a better source to get rid of that. Thanks for the share.

Similar Threads

  1. Adding new category attribute in Magento
    By golddev in forum Programming & Development
    Replies: 22
    Last Post: 24-01-2024, 10:52 PM
  2. How To Create, Edit, and Display Static Blocks Using Widgets
    By rocker in forum Webmaster & Administrator
    Replies: 3
    Last Post: 07-04-2021, 06:41 AM
  3. Magento Cache strategy for best performance
    By david in forum Magento Speed up, Performance and Optimize
    Replies: 3
    Last Post: 29-05-2014, 08:10 AM
  4. Magento Module Development - Part 2 - layout and blocks
    By rocker in forum Programming & Development
    Replies: 0
    Last Post: 22-04-2013, 07:31 AM
  5. How to configuring APC cache for Magento?
    By david in forum Programming & Development
    Replies: 1
    Last Post: 24-03-2013, 09:33 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •