Event Observer is a design pattern implementation of Magento 2. It is based on publish-subscribe pattern. Magento core code dispatches various events in different scenarios throughout the application.
Third party/Custom modules can trigger or execute a particular action based on the event.
Long back in mydons we have posted an article about event observer in Magento 1 version.
Event Observer sample use cases
- New customer registration event, can notify admin about the new user.
- Customer Login event, can use event observer to block the user from logging in.
- Add to Cart, can add a custom logic like adding free product along with the particular product
- Place order, cancel order events, can pass the order data to third party systems.
For this example lets take an example scenario where we want to notify admin user about newsletter subscription.
Step 1: Create the module activation file and registration.php file
Step 2: Create a di.xml file in etc/frontend/events.xml. Define the event responsible for newsletter subscription. Every model in Magento will have a special property called _eventPrefix . Each Core model Class has some special events like “eventprefix_save_before”, “eventprefix_save_after”
Once after defining the event name, declare the observer name it can be a any unique id in small case. In the instance Property specify the actual class name which handles the event
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<observer name="mydons_newsletteralert_adminnotification" instance="Mydons\NewsletterAlert\Observer\AdminNotification"/>
Step 3: Define the Actual observer class as shown below. we will include just a success message to indicate that our observer is been called.
class AdminNotification implements \Magento\Framework\Event\ObserverInterface
public function __construct(
$this->messageManager = $messageManager;
public function execute(\Magento\Framework\Event\Observer $observer)
$this->messageManager->addSuccessMessage(__("Observer Called Successfully. Add Your Custom code logic here"));
//Add Your Custom Logic Here