Magento 2 Create Events – Observer in Magento 2
Magento 2 Create Events – Observer in Magento 2
Create Events – Observer in Magento 2 ,Event observers consist of two main components:
- Event: An event is a trigger point within the Magento codebase where developers can hook in their custom logic. These events are typically defined using XML files in Magento modules.
- Observer: An observer is a PHP class that contains the logic to be executed when a specific event occurs. Observers are registered for events in XML configuration files, and they implement the
ObserverInterface
interface, which requires them to have anexecute()
method.
When the event is dispatched, Magento’s event manager notifies all registered observers for that event, and each observer’s execute()
method is called in turn. This allows developers to respond to events and perform tasks such as modifying data, sending notifications, or triggering additional processes.
Overall, event observers provide a flexible and powerful mechanism for extending Magento’s functionality and customizing its behavior to meet specific business requirements without directly modifying the core codebase.
How to Create Events – Observer in Magento 2
File: app/code/Latestblog/HelloWorld/Controller/Index/Test.php
Step 1.
Firstly we need to create a Module like:
registration.php
etc/module.xml
And create folder on root Controller/
Add below class name of controller/Index/Test.php
Step 2.
Create a event file: events.xml
File: app/code/Latestblog/HelloWorld/etc/frontend/events.xml
Add event.xml file and define and pass event name,instance Observer/ChangeDisplayData.php
Step 3.
Module Root:
Latestblog/HelloWorld/Observer/ChangeDisplayData.php
Add ChangeDisplayData.php class
Step 4: Flush cache and check the result
http://www.latest-blog.com/latestblog/helloworld/test
Result:
Latestblog – Event
Execute event successfully.