Programmatically: How to create custom Magento event handlers
Step 1: Create a new module
Create a new directory for your module in app/code/local (or app/code/community if you want to share it with others). For example, let's create a module called MyCompany_MyModule.
Inside the MyCompany_MyModule directory, create the following files: etc/module.xml: This file defines the module and its dependencies. etc/config.xml: This file defines the configuration for your module. Model/MyEventHandler.php: This is where you'll put your event handler code.
Here's an example of what these files might look like:
// app/code/local/MyCompany/MyModule/etc/module.xml
MyCompany MyModule
1.0.0
My custom Magento module
Magento_Core
// app/code/local/MyCompany/MyModule/etc/config.xml
true
local
// app/code/local/MyCompany/MyModule/Model/MyEventHandler.php
class MyCompany_MyModule_Model_MyEventHandler
{
public function __construct()
{
// Initialize your event handler
}
public function salesOrderPlaceAfter(Varien_Event_Observer $observer)
{
// Code to run when the order is placed goes here
// You can access the order object using $observer->getEvent()->getOrder()
}
}
Step 2: Register the event handler
In your config.xml file, we defined the event handler by adding the following code: