The Event Observer Mechanisms under Magento2

Today we will see how the mechanims so well known of event/observe is working under magento2. This tutorial is part of a magento2 training, if you have not yet done so, I invite you to start with the first article before you continue. For this tutorial, we will start from the code of the previous tutorial.

Presentation of the mechanism of Events/Observers

The mechanism of observation is one of the basic mechanisms that are regularly found in Object Oriented Programming (OOP). We define an object "observer" whose role is to constantly watch what happens on magento and to perform a precise function when an event is triggered. The "Event" is called by a method called displatch. When you make a dispatch of an event, all the observers associated with this event will be called.

Declaring an event under magento2

A magento2 Event is triggered using the EventManager (Magento\Framework\Event\Manager class), this class is automatically obtained in our controllers when we extend the \Magento\Framework\App\Action\Action class Once added to your class, you can now use this object to trigger an event via the dispatch method:

$this->eventManager->dispatch('pfay_contacts_event_test');

You notice that we pass a variable of type string to the dispatch method, it is the name of the event. Indeed, each event has a name here "pfay_contacts_event_test1" that will allow to attach one or more observers. We will create a new action to trigger our event. So create the /app/code/Pfay/Contacts/Controller/Test/Myevent.php as follows :

<?php
namespace Pfay\Contacts\Controller\Test;

use Magento\Framework\App\Action\Action;

class Myevent extends Action
{
    public function execute()
    {

        $this->_eventManager->dispatch('pfay_contacts_event_test');
        die('test');
    }
}

Theoretically if you comment on the line with the event manager, you should see "test" for the moment when you go to http://www.magento2.lan/contacts/test/myevent. You can then uncomment the line after your test.

Create an Observer under magento2

Under Magento, an Observer is a class that implements the Magento\Framework\Event\ObserverInterface interface, meaning that it takes a method that runs with an \Magento\Framework\Event\Observer argument. We will therefore create our class like this:

<?php
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

/**
 * Class TestObserver
 */
class TestObserver implements ObserverInterface
{

    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        die('test observer');
    }
}

For the moment if you go back to your action, nothing happens yet but observers will theoretically run and display "test observe" instead of "test". There is one thing left to do to make it work ... link the event and the observer.

Associating an Observer to an event under magento2

Observers are therefore elements that trigger functions when calling the dispatch() method of an event. An observer is associated with event via the name of the event. This association is maintained in the events.xml file. Let's create our events.xml file like this:

<?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="pfay_contacts_event_test">
        <observer name="pfay_contacts_observer_test" instance="Pfay\Contacts\Observer\TestObserver" />
    </event>
</config>

In this file, a new event element is declared in "events", this event will be called "pfay_contacts_event_test" and will trigger the observer which named is "pfay_contacts_observer_test" and it will be represented by the class "Pfay\Contacts\Observer\TestObserver ". So now during the dispatch("pfay_contacts_observer_test"), our observer is triggered.
Indeed if we go back to our page http://www.magento2.lan/contacts/test/myevent, we see well "test observe" appears so our Observer is working.

Using a native magento2 events

To use the native events of magento nothing more simple...it is exactly the same. You can download the "cheat sheet magento2" PDF at the bottom of this tutorial, you can print this sheet easily, it list all the native Events of magento2. Taking an example, you want to run your Pfay\Contacts\Controller\Test\Myevent Observer when adding a product. So I look in the "cheat sheet" and you can see that there is a native event called "checkout_cart_add_product_complete" You will then edit your file events.xml in order to add your observer in the event. So edit the events.xml file like this:

<?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="checkout_cart_add_product_complete">
        <observer name="pfay_contacts_observer_test" instance="Pfay\Contacts\Observer\TestObserver" />
    </event>
</config>

Then go on a product sheet and add the product to the basket. You will be redirected to a blank page with "test observe". So my observer has been taken into account.

Overloading an Observer under magento

To overload an Observer on Magento it's as usual, just add a preference in di.xml to overload our Observer. So edit the /app/code/Pfay/Contacts/etc/di.xml file to add this line:

<preference for="Pfay\Contacts\Observer\TestObserver" type="Pfay\Contacts\Observer\SurchargeObserver" />

And create the Overload Observer object (/app/code/Pfay/Contacts/Observer/SurchargeObserver.php) like this:

<?php
namespace Pfay\Contacts\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

/**
 * Class TestObserver
 */
class SurchargeObserver implements ObserverInterface
{
    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        die('surcharge observer');
    }
}

Go back on a product sheet and add the product ... I have "overload observe" which appears...so my observer has been overloaded ! This is the end of this tutorial, if you can not make it work feel free to download the code via the links just below. If after analyzing this code you still can not make it work do not hesitate to leave me a message down in the comments and I will answer as quickly as i can. Do not hesitate if you have any questions.
Books that can help you :
  • Livre Magento 2 Developer's Guide by Branko
  • Livre Mastering Magento2 Second Edition
  • Livre Magento 2 Cookbook
Questions about this lesson
No questions for this lesson. Be the first !

You must be logged in to ask for help on a lesson.