B-219 Sec-55 Noida, India
+918010221733

Automatically refresh Magento cache

In Magento, whenever you make changes to products, static blocks, etc, it recognizes that the data in the database is no longer the same as what it has in the cache. Unfortunately, Magento doesn’t realize what cache data is different, just that something is different.

Traditionally, you will need to go into System > Cache Management and refresh the invalidated cache types, but I’ve overcome this by using a cron job that runs every time cron runs on the server, and calls a function to refresh the cache automatically.

Whenever you make changes, magento fires events. There are listeners to these events that invalidate the relevant cache. As for why it does this (and why it doesn’t automatically refresh) this is ultimately a design decision, but probably has something to do with being able to stage content. For example, you could make changes to several products that all relate to one another, and can then refresh the cache.

Before using this functionality, you’ll need to ensure that cron is set up and configured correctly on your server. I’m not the right person to ask regarding this, but I’m sure google has some tutorials relevant to your server configuration.

Create a module (or use an existing module) that you can use to set up a cron job for refreshing the cache.

Create a file: {{namespace}}/{{modulename}}/Model/Observer.php

Inside that file:

  <?php

  class <namespace>_<modulename>_Model_Observer {

    public function refreshCache() {
      try {
        $allTypes = Mage::app()->useCache();
        foreach($allTypes as $type => $blah) {
          Mage::app()->getCacheInstance()->cleanType($type);
        }
      } catch (Exception $e) {
        // do something
        error_log($e->getMessage());
      }
    }

  }

In your module’s etc/config.xml:

  <config>
    …
    <crontab>
      <jobs>
        <{{modulename}}_refresh_cache>
          <schedule><cron_expr>* * * * *</cron_expr></schedule>
          <run><model>{{modulename}}/observer::refreshCache</model></run>
        </{{modulename}}_refresh_cache>
      </jobs>
    </crontab>
    …
  </config>

Now as long as cron is configured correctly on your server, the cache will update automatically as often as cron runs.

(Visited 76 times, 1 visits today)

Leave a reply

You must be logged in to post a comment.