An Introduction to Events in Magento 2

Posted by Navarr Barnier

April 20, 2016 | 10:30 AM

Share this blog on:     

magento_2_events.pngMagento Events have been an impactful tool in Magento, and they have made the jump to Magento 2 as well. Events in Magento 2 have some changes and enhancements, however, so here is an introduction to events and some information on how to use them in Magento 2.

First, What Are Events?

Events are exactly what they sound like: something that happens. In Magento-specific terms, they are handlers that allow other parts of your code to react to actions that take place in the application. 

For instance, you may want to add a free catalog to an order when someone places a product into his or her cart. By listening for, or observing, that event, you can be sure the appropriate action will be taken.

Why Should I Use Events?

As a developer, using events can greatly simplify your code and allows for re-use. By not defining your requirements directly within your controllers or block classes, you reduce a lot of clutter and you can often avoid rewriting core Magento block classes. This makes for cleaner, more manageable modules. 

Observing an Event

An event observer is defined in your extension's config.xml. Perhaps you have a module named, for example, Acme_AddCatalog, that automatically adds a physical catalog to a customer's cart. We will want to run this when another product is added to the cart. 

Here is an example of how that might look in your module. We will only be calling attention to the implementation of the event, rather than providing an entire extension.  

You would first add the XML that specifies you’re listening for an event. You would do this by creating (if it doesn’t already exist) an events.xml located at etc/frontend/events.xml. The insides of this file would look something like this:

<?xml version="1.0" encoding="utf-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_add_product_complete">
        <observer name="acme_addcatalog_add_product_complete" instance="Acme\AddCatalog\Model\Observer" />
    </event>
</config>

There are only a couple things to point out:

  • checkout_cart_add_product_complete is the name of the event (as obvious by <event name="">) we want to observe, which in this case is the event that fires after a product has been completely added to the cart.
  • acme_addcatalog_add_product_complete (<observer name="">) is a unique name for our Observer. Most modules use their own name as part of the identifier to ensure its uniqueness.
  • Acme\AddCatalog\Model\Observer is the Fully Qualified Name – or FQN – of the class we want to instantiate to observe this event.

If you’re familiar with Magento 1 you’ll notice we don’t need to specify whether or not it’s a singleton, nor do we need to specify the method to call. Since Magento 2 uses dependency injection, you’ll want your observer to be constructed so that it can pull those dependencies in – specified by the usual constructor. For Magento 2, the method “execute” will be called automatically. To see that in action, take a look at our example Observer class (located in our module as Observer/AddCatalogToCart.php).

<?php

namespace
Acme\AddCatalog\Observer;
 use Magento\Catalog\Model\Product;
 use Magento\Framework\Event\Observer;
 use Magento\Framework\Event\ObserverInterface;
 class AddCatalogToCart implements ObserverInterface
 {
     public function execute(Observer $observer)
     {
         $event = $observer->getEvent();
         /** @var Product $product */
       
$product = $event->getData('product');
         if (!$this->isCatalogProduct($product)) {
             // TODO Add the catalog to the cart!
       
}
     }
     private function isCatalogProduct(Product $product)
     {
         // TODO Check if the product being added is the catalog we want to add
   
}
 }

As you can see, we have our execute method, which takes in the Magento\Framework\Event\Observer class as a parameter. From here, we can grab the event (an instance of Magento\Framework\Event), and from that we can grab information about the event.

If we search the Magento codebase for the name of the event we’re listening to, we’ll find this little bit of code:

$this->_eventManager->dispatch(
     'checkout_cart_add_product_complete',
     ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
 );

This tells us what variables we can grab from the event. What we want is the $product, as you can see in our snippet from the helpful TODOs. We would then use this product to determine whether or not it’s the catalog we want to add ourselves. Otherwise, we might end up in a terrible loop, adding thousands and thousands of catalogs to our customer’s cart – with no end in sight!

Resources

Unfortunately for us, Magento has not currently published a complete list of events in Magento 2. Luckily, however, the community is here to help!

Cyrill Schumacher has published a fantastic post with a complete list of events in Magento 2.

However, there’s no substitute for experimentation! While his list is a fantastic place to start, you’d be well advised to read through some of the core code to find out what’s going on with each individual event so you know the surrounding context and the state of the objects you can get from them. It’s definitely an exercise in patience if you’re venturing into an event type you haven’t used before, but you may find the usefulness of the event to be well worth the effort. 

value of certified developers

Topics: Magento, Magento Technical, Magento 2

About Navarr Barnier

Navarr is a Magento Developer for the Briteskies team. His professional interests include the semantic web and ways to improve user experience beyond the web page. Outside of the office, Navarr enjoys playing Rocket League, helping to manage a Minecraft network, and spending time with his daughter, Charlotte.

Search

Subscribe to Email Updates

magento-platform-checklist
New Call-to-Action

Contact Us

B2B-2.0

Recent Posts