Magento2 | PWA | GraphQL

How to Create Custom Event Observer and Dispatch it in Magento 2


In this example i will show you How to create a custom event observer and dispatch our custom event in Magento 2.

Step 1- Declaration of event in your Controller or Model class

public function afterSave()
{
    if ($image = $this->getImage()) {
        $filePath = new DataObject(['path' => self::MEDIA_SUBDIRECTORY_PATH . $image]);
        $this->eventManager->dispatch('magelearn_create_webp', ['magelearn_filepath' => $filePath]);
    }

    return parent::afterSave();
}

Here, we have dispatched our custom event named "magelearn_create_webp"

NOTE

The dispatch method will receive 2 arguments: an unique event name and an array data.

For this we need to create a file events.xml at app / code / {vendor name} / {module name} / etc / and declare out custom observer and event name as shown in the code below :

Step 2- Declare our custom event name and observer class

<?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="magelearn_create_webp">
		<observer instance="Magelearn\SliderExtended\Observer\Slider\Uploadfiles" name="s3amazon_slider_image_upload"/>
	</event>
</config>

In this file, under config element, we define an event element with the name is the event name which was dispatch above.

The class which will execute this event will be define in the observer element by instance attribute.

Step 3- creating custom observer method : 

Now, we will create a custom observer file named Uploadfiles.php at app / code / {vendorname} / {modulename} / Observer /

public function execute(Observer $observer)
{
    $image = $observer->getData('magelearn_filepath');
    $filename = $image->getPath();
    $this->logger->info('filepath is'.$filename);
    //...do with your data...//
}

The excute method of this file will get called when the dispatcher event is called which we have prepared above in the first file.

Now use the data to perform any custom operation which is required and after that the code after the dispatch event will get executed .

So in this way you can create and call your own custom event easily.


0 Comments On "How to Create Custom Event Observer and Dispatch it in Magento 2"

Back To Top