Magento How to create Observer


An Observer, also called 'listener', will listen to your program to detect events. When there is an event taking place, it will perform an action defined by you.


Step 1: Folder Structure


Magento 1


The Observer will be created in the previous extension, which is already created: app/code/local/MageCheck/Tutorial. We will have to edit the existing config.xml file and add a new php file like in the steps below.

Magento 2


In order to create the following Observer we will add some new extra content in the previous extension, already created: app/code/MageCheck/Tutorial. We will have to create a new php file and a new xml file inside. Let's follow the steps below!


Step 2: Declare Observer


Magento 1


File path: app/code/local/MageCheck/Tutorial/etc/config.xml

... <events> <cms_page_prepare_save> <observers> <MageCheck_Tutorial_Model_Observer> <type>singleton</type> <class>magecheck_tutorial/observer</class> <method>customObserver</method> </MageCheck_Tutorial_Model_Observer> </observers> </cms_page_prepare_save> </events>

Magento 2


File path: app/code/MageCheck/Tutorial/etc/events.xml

<?xml version='1.0'?> <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='urn:magento:framework:Event/etc/events.xsd'> <event name='magecheck_tutorial_custom_observer'> <observer name='mc_custom_observer' instance='MageCheck\Tutorial\Observer\Test' /> </event> </config>


Step 3: Create Observer Class


Magento 1


File path: app/code/local/MageCheck/Tutorial/Model/Observer.php

class MageCheck_Tutorial_Model_Observer extends Varien_Event_Observer { public function __construct() { // ... } public function customObserver($observer) { echo 'MageCheck Observer!'; } }

Magento 2


File path: app/code/MageCheck/Tutorial/Controller/Index/Test.php

<?php namespace MageCheck\Tutorial\Controller\Index; class Test extends \Magento\Framework\App\Action\Action { public function execute() { echo 'MageCheck Observer!'; exit; } }

Do not forget to clean Magento Cache.


This is the sample way to create an Observer in Magento!