Listening to Observer in magento

In magento if you wish to listen to certain events from the magento framework itself, or from your own custom event. The following code will help you to listen to a event.

Add this to the events.xml under the etc folder

If it is a backend event that under etc/adminhtml/events.xml

<event name="controller_action_catalog_product_save_entity_after">
        <observer name="CProductSavedByAdmin" instance="Company\Module\Observer\ProductSavedByAdmin" />
</event>
namespace Company\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class ProductSavedByAdmin implements ObserverInterface
{
    /**
     * @param Observer $observer
     */
    public function execute(Observer $observer): void
    {
	    // do whatever you wish to do here
    }
}

It is a good way to implement new changes in magento or any other framework using events. If you are using events, the code which you have already written does not need to be changed or refactored.

Imagine a situation whereby you register a user. After writing user details in to the database. You can trigger an event new_user_registered.

We send a thank you email to the user to let him know that he has been accepted on our website. His account has been created.

Now the product owner wishes that once a new user is registered, SAP would also like to save user details. In order to achieve this functionality as a programmer you could just listen to the event new_user_registered in a new class. In this class you could write the code to send the user details to SAP. This way you do not have to touch other aspects of user registration process. The classes and their unit tests will run isolated and we will not have a huge service class doing everything for us.

Happy Coding

what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news

Articles

PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.