Avoid recursive calls in Magento observer classes

Since I was recently asked how to avoid recursive calls in Magento observer classes when for instance calling save() in an xxx_save_after event observer: Simply use an internal processing flag.

class My_Products_Model_Observer {

  /** @var boolean flag to signal successful processing of current model entity */
  private $_isProcessed = false;

  /**
   * Handle catalog_product_save_after event.
   * @param Varien_Event_Observer $observer
   */
  public function catalog_product_save_after(Varien_Event_Observer $observer) {
    try {
      $product = $observer->getEvent()->getProduct();

      // do some processing...

      if(!$_isProcessed) {
        $this->_isProcessed = true; // avoid recursion
        $product->save();
      }
    } catch (Exception $e) {
      Mage::log($e->getMessage()); // do some logging
    }
  }
}

That’s it – Sometimes things can be very simple 😉

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.