Magento1 vs Magento2. Configurations Observers and Events (Developer Certification Exam)

Magento1 vs Magento2. Configurations Observers and Events (Developer Certification Exam)

Events are commonly used in applications to handle external actions or input when, for example, a user clicks a mouse. Each action is interpreted as an event. Events are part of the Event-Observer pattern. This design pattern is characterized by objects (subjects) and their list of dependents (observers). Events trigger objects to notify their observers of any state changes, usually by calling one of their methods. It is a very common programming concept that works well to decouple the observed code from the observers.

Magento 1 shares the same concept, although the execution is different. If you needed to trigger an event at a certain place in your code in Magento 1, it would be fired by calling Mage::dispatchEvent(), while in Magento 2 there is a special event manager class – Magento\Framework\Event\Manager that fires events. This class can be obtained through dependency injection by defining the dependency in your constructor.

Look for the mentioned notes in the code Magento1:

Mage::dispatchEvent(‘event_name’, $event_arguments);

This note is an “observer” that allows executing methods attached to it, transferring $event_arguments data array into methods.

Look for the mentioned notes in the code Magento2:


Event Observers in Magento1 can be configured and described in config.xml:

An observer class should have the method name declared in config.xml

Event Observers in Magento2 can be configured in a separate file event.xml. It should be created in <module-root>/etc directory, if observer is associated with globally events, or in <module-root>/etc/frontend and <module-root>/etc/adminhtml if observer is to only watch for events in frontend or adminhtml areas.

In instance attribute we declare observer class name. This class has to implement Magento\Framework\Event\ObserverInterface::execute(Observer $observer) method. The $observer object has an $event object (available through $observer->getEvent()), which contains the event’s parameters.

In Magento1 we can use automatically available events. For example:

This event triggered before saving object, if it extends Mage_Core_Model_Abstract class. When we create a new class, which extends Mage_Core_Model_Abstract, we can declare $eventPrefix = “namespace_modulename”  and use new event namespace_module_save_before.

There’s  the same ability in Magento2. In class Magento\Framework\Model\AbstractModel:

In Magento1 and Magento2 we have the same automatically available events.



Using observers in Magento is a good practice, but in process of development in Magento1 often this tool was not enough and we had rewrite classes. So in Magento2 a new tool “plugin“ was added.

Post a new comment

BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *