https://embed.notionlytics.com/wt/ZXlKd1lXZGxTV1FpT2lKak16QmpNV1JqWTJNd04yWTBaR0l4T1dSaVpqZGlPVE5tT1RCbU5UY3hOQ0lzSW5kdmNtdHpjR0ZqWlZSeVlXTnJaWEpKWkNJNklrbGpiM1pzV2pOcU1VUnBRM1ZUUm1WNFRtdHlJbjA9

What is an event?

An event is a user action or other occurrence that is detected by the system and triggers a response. Events are dispatched when certain actions are triggered, for example, when the user presses the button "pay" on your website, it is an event. Your order is saved? Again it is an event. When an event is dispatched, it can pass data to any observers configured to watch that event. Also, for more understanding, events are activities that the user performs in-store, for example, adding products to the cart, creating a new profile, etc.

Magento 2 comes with a lot of necessary core events that provide all the necessary things for the store, but sometimes there are requirements for custom events in the project that doesn't come with Magento 2 core events. In that case, it can be easily made.

What is a dispatcher?

A dispatcher is part of the event which dispatches or gets information from other modules. It can pass information to observers that can be later used for other actions.

What is an observer?

An Observer is a certain type of Magento class, also called a "listener", which will listen to your program to detect events. When there is an event taking place, it will perform an action defined by you, like influence general behavior, performance, or changing business logic. They are executed whenever a specific event for which they were set to listen is triggered. For example, after a customer registers an event will fire which the observer is listening to, for example, the observer can display a notification message - "Welcome Firstname Lastname".

Untitled

How to dispatch an event?

1. Create a new module

The first thing to do when making custom events or custom observers for the core events is to create a new module for them. How to create a Magento module?

2. Define a new event

Custom and core events can be dispatched by simply passing in a unique event name to the event manager when you call the dispatch function. Your unique event name is referenced in your module’s events.xml file where you specify which observers will react to that event.

You can make the custom event my_module_event_after subscribe-able by declaring the MyCompany/MyModule/etc/<AREA>/events.xml Replace <AREA> with a proper area code. What area code should I use?

<config xmlns:xsi="<http://www.w3.org/2001/XMLSchema-instance>" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="***my_module_event_after***">
        <observer name="my_module_event_after_observer" instance="MyCompany\\MyModule\\Observer\\MyEvent"/>
    </event>
</config>

3. How to dispatch events?