Magento 2 — Module — Create Observer
1 min readJul 16, 2019
Observer is a feature of Magento 2 Module to make an action on events such as User adds product to cart, User logins, etc.
So, how to make it?
1. Create etc/events.xml file
You can make them into a different areas:
- Global Area : <root>/etc/events.xml
- Front-End Area : <root>/etc/frontend/events.xml
- Back-End Area : <root>/etc/adminhtml/events.xml
Here’s a simple example of this file :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="<magento_event_name>">
<observer name="<VendorName_ModuleName_ObserverName>" instance="<VendorName>\<ModuleName>\Observer\<ClassName.php>" />
</event>
</config>
You can see what events Magento has here :
https://www.simicart.com/blog/magento-2-events-list/
2. Create Observer Class
Create a Class
that has execute
method on it. Why? Because Magento 2 will automatically calls execute
method. Here’s the example :
<?phpnamespace <VendorName>\<ModuleName>\Observer;use \Magento\Framework\Event\ObserverInterface;
use \Magento\Framework\Event\Observer;class CustomerLogin implements ObserverInterface
{
public function execute(Observer $observer)
{
// Type your code here
echo "Customer LoggedIn Cuk, ";
$customer = $observer->getEvent()->getCustomer();
echo $customer->getName(); //Get customer name
exit;
}
}
Don’t forget to flush the cache! And run it.