read

I always have to go digging to remember how to tap into Magento's events, so I'm writing this down, as much for my benefit as everyone else!

In the example below, I'm creating an extension that notifies the Magento admin on a customer's account creation.

Step 1: Create Extension

<?xml version=""1.0"" ?>
<config>
    <modules>
        <Birnie_CustomerCreateNotify>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Customer />
            </depends>
        </Birnie_CustomerCreateNotify>
    </modules>
</config>

<!-- /app/code/etc/modules/Birnie_CustomerCreateNotify.xml -->

Step 2: Find the Event

Using either Alan Storm's CommerceBug or this nice event cheat sheet, determine the event you'd like to observe. In my case it's customer_register_success.

It is also important to check out what is actually being passed with the observer object. In this case, I looked to the Customer Account controller and found the following:

    Mage::dispatchEvent('customer_register_success',
        array('account_controller' => $this, 'customer' => $customer)
    );

This will allow us to get the customer that registered by calling:

$observer->getCustomer()

Step 3: Create the extension files

Create the following directories/files:

  • /app/code/local/Birnie/CustomerCreateNotify/etc/config.xml
  • /app/code/local/Birnie/CustomerCreateNotify/Model/Observer.php

Step 4: Populate extension's config.xml

<config>
    <modules>
        <Birnie_CustomerCreateNotify>
            <version>0.1.0</version>
        </Birnie_CustomerCreateNotify>
    </modules>
    <global>
        <models>
            <customercreatenotify>
                <class>Birnie_CustomerCreateNotify_Model</class>
            </customercreatenotify>
        </models>
        <events>
            <customer_register_success>
                <observers>
                    <customercreatenotify>
                        <type>singleton</type>
                        <class>Birnie_CustomerCreateNotify_Model_Observer</class>
                        <method>notifyAdmin</method>
                    </customercreatenotify>
                </observers>
            </customer_register_success>
        </events>
    </global>
</config>
  • customer_register_success refers to the event
  • class tells the class (and location) of the observer file
  • method refers to the actual method in the file to which the observer object will be passed.

Step 5: Create the Observer Model file

class Birnie_CustomerCreateNotify_Model_Observer
{
    public function notifyAdmin($observer)
    {
        die(""Worked"");
    }
}

Step 6: Clear Cache

Clear your cache and try to create an account; if all went well (and the account creation was successful), should be interrupted by a rude ""Worked"" message.

Blog Logo

Phil Birnie


Published

Image

Phil Birnie

Full Stack Web Developer from Columbus, Ohio

Back to Overview