Mage Check Facebook iconFacebook MAGE CHECK Mage Check Linkedin iconLinkedin MAGE CHECK Mage Check Skype iconSkype MAGE CHECK

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

... <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>

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

Magento 2

<?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>

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

Step 3: Create Observer Class

Magento 1

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

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

Magento 2

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

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

Do not forget to clean Magento Cache.

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

Contact us

Have you decided on an online Business Plan website?