19
votes

How can I add a custom event in Magento like "done_some_thing"?

I am coding for a shopping cart which gives a certain % discount for the customers who comes through a particular link, and want to show the same in both Cart and Checkout Page

1

1 Answers

32
votes

To dispatch an event, use the Mage::dispatchEvent function (%magento%/app/Mage.php around line 425). Calls look like this:

$data = array( 'somedata' => 'foo', 'layout' => $this->getLayout());
Mage::dispatchEvent('my_event_name', $data);

In order to observe an event, specify the observer in the config.xml file of your extension.

<config>
    <global>
        <events>
            <my_event_name>
                <observers>
                    <myextension>
                        <type>singleton</type>
                        <class>myextension/observer</class>
                        <method>someMethodName</method>
                    </myextension>
                </observers>
            </my_event_name>
        </events>
    </global>
</config>

Create a corresponding class and method (Observer.php) and you're set to go:

class Myextension_Model_Observer {
    public function someMethodName($event) {
        $layout = $event->getLayout();
        $someData = $event->getSomedata();
    }
}