Magento 2 Event Observer with simple example

Overview

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.
https://mydons.com/simple-example-using-magento-event-observer

Event Observer sample use cases

  1. New customer registration event, can notify admin about the new user.
  2. Customer Login event, can use event observer to block the user from logging in.
  3. Add to Cart, can add a custom logic like adding free product along with the particular product
  4. 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.

Example

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

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.

Final output