Mini Tutorial:
Dispatch Your Own Event in Magento

There is usually quite a bit of documentation on creating your own observer in Magento, but there are times where you need to dispatch your own event in a custom module which others can hook into. We can search core code to find several places where events are dispatched, and we can find this by searching through.

For example, let’s look app/code/core/Mage/Checkout/Model/Type/Onepage.php in the function saveOrder(). We can see the dispatch code here right before we return $this:

Mage::dispatchEvent(
            'checkout_submit_all_after',
            array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
        );

If we hooked into this event, we have access to the order object, the quote object, and the recurring profiles. We can change these class instances and have them retained, as the objects are passed by reference (well, not really, but it is easier to say. See http://php.net/manual/en/language.oop5.references.php for clarification) As you usually get spoiled by passing objects, I recently forgot that other non-object variables need to be passed by reference.

Mage::dispatchEvent('my_custom_event’, array(
                'email'             => &$email,
                'fields'            => &$fields,
            ));

All we have to do is use standard PHP “pass by reference” flag ‘&’. Remember in the function to change the original variables like so:

$event = $observer->getEvent();
$fields = $event->getFields();
$fields[0] = ‘changed’;
$observer->getEvent()->setFields($fields);

Remember to create your observer in standard Magento fashion and you should be good to go with a custom dispatch! Enjoy. 🙂