First, we registered a new Module with Name Jeff_Helloworld:
#app/etc/modules/Jeff_Helloworld.xml true local
Second, we create Jeff_Helloworld module by generating the folder app/code/local/Jeff/Helloworld/etc/config.xml file, which is shown as following:
#app/code/local/Jeff/Helloworld/etc/config.xml 0.1.0 Jeff_Helloworld_Block Jeff_Helloworld_Helper Jeff_Helloworld_Model Jeff_Helloworld helloworld jeff_helloworld.xml
In this file, we just tell magento, the name of new module and the locations of blocks, model and helper classes. We also register a route helloworld. So the URL (http://www.domain.com/helloworld/controller/action) will point to folder app/code/local/Jeff/ Helloworld/controllers/ControllerController.php
Third, we create sub-folder as app/code/local/Jeff/ Helloworld/controllers to put our Controller classes. The first Controller is named “IndexController” and the action is called “index”.
class Jeff_Helloworld_IndexController Extends Mage_Core_Controller_Front_Action { public function indexAction() { $this->loadLayout(); $parameters = array( 'product'=>Mage::getModel('catalog/product')->load(1), 'category'=>Mage::getModel('catalog/category')->load(10) ); Mage::dispatchEvent('helloworld_register_visit', $parameters); $this->renderLayout(); } }
To dispatch an event, the Mage::dispatchEvent() function is used. In the indexAction( ) function, we will dispatch an event called helloworld_register_visit.
Fourth, we need a mechanism to see whether the event is dispatch or not. To test that the code works, we have to debug the Mage_Core_Model_App::dispatchEvent() function. In order to override this method that is magento core code, we need copy the app/code/core/Mage/Core/Model/App.php file to your local folder. Creating this folder structure as app\code\local\Mage\Core\Model and copy the App.php file into it. Then modify the dispatchEvent() function as shown below:
public function dispatchEvent($eventName, $args) { foreach( $this->_events as $area => $events) { if(!isset($events[$eventName])) { $eventConfig = $this->getConfig()->getEventConfig($area, $eventName); if(!$eventConfig) { $this->_events[$area][$eventName] = false; continue; } $observers = array(); foreach( $eventConfig->observers->children() as $obsName => $obsConfig) { ............ } } }
Last, clear the cache and reload the page in the frontend and have a look at the var/log/system.log file. You are supposed to see some event names fired, inside there is an item named ‘helloworld_register_visit’ event.