How to cache custom data into Magento

Caching data in Magento can have a significant impact on the performance of your site. Here’s how a few lines of code you can easily cache any data type.

<?php
// ...
$cacheId = 'my_cache_id';
if (false !== ($data = Mage::app()->getCache()->load($cacheId))) {
    $data = unserialize($data);
} else {
    $data = $this->getMyHeavyData();
    Mage::app()->getCache()->save(serialize($data), $cacheId);
}
//...

And that’s all ;)

6 Responses to “How to cache custom data into Magento”

  1. mohammed abdelrahman says:

    Thanks!

  2. Vlad N. says:

    Thanks dude, this helped me alot.

  3. Luis says:

    Hello,

    Where do you use this lines?

    THank you for your answer.
    Cheers

  4. How can one check if a cache key is enabled or disabled? I want to tag my caching onto BLOCK_HTML caching and have it only happen if that is enabled.

  5. MAXIME HURAN says:

    I found how to proceed :

    $cacheId = ‘my_cache_id';

    if (Mage::app()->useCache(‘block_html)) {
    if (false !== ($data = Mage::app()->loadCache($cacheId))) {
    /* PROCESS CACHE */
    $mydatas = unserialize($data);
    } else {
    /* PROCESS NO CACHE */
    $mydatas = “toto”;
    Mage::app()->saveCache(serialize($fapiResponse), $cacheId, array(‘block_html’), 86400);
    }
    } else {
    /* PROCESS NO CACHE */
    }

    If you are in a block inherits Mage_Core_Block_Abstract you can use :
    self::CACHE_GROUP instead of “block_html”
    $this->getCacheTags instead of array(‘block_html’)

Leave a Reply

* Required fields

Categories