Programmatically Set and Unset Event Triggering for Custom Module

event-observer

So here is the scenario that I need to achieve. I have a custom module. In it's controller, I am setting a cookie when some conditions are met. I need to check the status of this cookie if any other url request is made through an observer (event using is controller_action_predispatch). When some conditions are met, I will delete this cookie and then I don't want to trigger the event any more (or till next time when the cookie sets through my controller.).

An example shown below. My custom controller looks like this

File: app\code\local\Namespace\Module\controllers\CustomController.php

public function someAction()
{
      if (<some_condition_met>) {
          Mage::getModel('core/cookie')->set('cookiename', 'value', 7200);
          $this->activateObserver($eventname, $modulename, $methodname); // I need this. Later for all action it should observer the event that is specified inside `activateObserver()`
      }
}

activateObserver() will starts event triggering. Now onwards, for every action, it should observe to my custom obsever method.

Now my observer method looks like this.

File : app\code\local\Namespace\Module\Model\Observer.php

public function myObserverMethod($observer)
{
        if (<some_condition_met>) {
             Mage::getModel('core/cookie')->delete('cookiename');
             $this->deactivateObserver($eventname, $modulename); //this should deactivate event observation. Now onwards I dont need to observe this event
        }
}

Now here deactivateObserver() deactivate event triggering from my module.

Why I need this ?

This is because, I am observing to controller_action_predispatch. I just want to observe this event during the life time of my cookie. This cookies life time is 2 hours maximum. Since the event that I am observing occurs for every action, it would be definitely a burden and I need to avoid this.

Is it possible in Magento ? Share your thoughts.

Best Answer

This is not possible - the event will be fired each time for every module including yours. You can only programmatically deactivate the event observer completely, but this is not what you are after.

So the thing you would normally do is to directly check in your observer method if the cookie is set and if it is not set, return instantly:

public function myObserverMethod($observer)
{
    if (<cookie_not_set>) {
        return;
    }
    // do whatever you need to do
}

I understand your point that you do not want to do it like that, because the event is fired so often. The only solution I see here is that you could potentially use a more specific event which is not fired that often like controller_action_predispatch_cms or controller_action_predispatch_cms_index_index. Have a look at the event dispatching code here in order to find a suitable event.

Related Topic