Book Image

Magento 2 Development Cookbook

Book Image

Magento 2 Development Cookbook

Overview of this book

With the challenges of growing an online business, Magento 2 is an open source e-commerce platform with innumerable functionalities that gives you the freedom to make on-the-fly decisions. It allows you to customize multiple levels of security permissions and enhance the look and feel of your website, and thus gives you a personalized experience in promoting your business.
Table of Contents (13 chapters)
12
Index

Adding an event observer


If you read the previous recipe, you know how to fire an event using the dispatch() function. In this recipe, you will learn how to execute some code when an event is dispatched and what we can do with it.

Getting ready

In this recipe, we will add two event observers. The first one will catch the event that we created in the previous recipe. The second event listener (observer) will hook into the add to cart action of a product.

In this recipe, we will work further on the Packt_HelloWorld module from the previous recipes. Ensure that you have the right code files installed for this recipe.

How to do it...

In this tutorial, you will discover how to listen for an event and execute your code by performing these steps:

  1. When we want to add an event observer for the helloworld_register_visit event, we have to add the following configuration to the app/code/Packt/HelloWorld/etc/events.xml file with the following content:

    <?xml version="1.0"?>
    <config xmlns:xsi="http:...