Choosing Between Plugins and Observers in Magento 2: A Developer’s Guide

If you’re familiar with Magento 2’s architecture, you likely know that there are multiple ways to modify core functionality without changing the core code. The two most commonly used methods are Observers and Plugins. Both play vital roles in extending and customizing Magento 2, but knowing when to use each can sometimes be challenging.

Before diving into this comparison, make sure you’ve read our previous blog on Overriding in Magento 2: Mastering Preferences, Plugins, and Event Observers to understand the foundational concepts of Magento 2 customization.

Now, let’s explore the key differences between Observers and Plugins, along with their best use cases in Magento 2.

What Are Observers in Magento 2?

Observers in Magento 2 are part of the Event-Observer design pattern. They are triggered when specific events occur within the system. You can think of them as “listeners” that react to various Magento events (like “checkout”, “order creation”, etc.).

Key Characteristics of Observers:

  1. Event-based: Observers react to pre-defined events in Magento.
  2. Global in Scope: Observers can listen to core Magento events as well as custom events.
  3. No Return Modification: Observers do not modify the return value of a function, they just execute additional logic based on the event.
  4. Multiple Observers per Event: Multiple observers can respond to a single event.

Example Use Case:

An observer can be used to perform an action after an order is placed, like sending a custom email notification.

<!-- events.xml -->
<?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="checkout_submit_all_after">
        <observer name="custom_order_observer" instance="Vendor\Module\Observer\OrderObserver" />
    </event>
</config>
<?php
namespace Vendor\Module\Observer;

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

class OrderObserver implements ObserverInterface
{
    public function execute(Observer $observer)
    {
        // Add your custom logic here
        $order = $observer->getEvent()->getOrder();
        // Do something with the order data
    }
}

What Are Plugins in Magento 2?

Plugins, also known as Interceptors, allow you to modify or extend the behavior of public methods in Magento classes without overriding them directly. Plugins work at the method level, giving you the flexibility to control the flow of code before, after, or around the method execution.

Key Characteristics of Plugins:

  1. Method-Level Customization: Plugins work at the method level, allowing fine-tuned control.
  2. Three Types:
    • Before Method: Runs before the original method.
    • After Method: Executes after the original method has run.
    • Around Method: Wraps around the original method to modify its behavior entirely.
  3. Return Value Modification: Plugins can modify the return values of the original method.
  4. Order of Execution Matters: Plugins can be executed in a specific order using the sortOrder attribute.

Example Use Case:

A plugin can be used to modify the price of a product when it’s added to the cart.

<!-- di.xml -->
<type name="Magento\Catalog\Model\Product">
    <plugin name="custom_product_plugin" type="Vendor\Module\Plugin\ProductPlugin" />
</type>
<?php
namespace Vendor\Module\Plugin;

class ProductPlugin
{
    public function beforeGetPrice(\Magento\Catalog\Model\Product $subject)
    {
        // Modify price before the original method executes
        return [$subject->getPrice() * 1.10]; // Increase price by 10%
    }

    public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result)
    {
        // Modify the result after the original method executes
        return $result + 5; // Add $5 to the original price
    }

    public function aroundGetPrice(\Magento\Catalog\Model\Product $subject, callable $proceed)
    {
        // Completely override the original method's functionality
        return 100; // Return a fixed price of $100
    }
}

Observers vs Plugins: Key Differences

Feature Observers Plugins
Trigger Reacts to system or custom events Hooks into specific methods
Customization Scope Event-level Method-level
Return Value Modification Cannot modify return values Can modify return values
When to Use For broad actions that respond to an event For fine-grained control over a class’s method execution
Order of Execution No control over the order of execution Control via sortOrder
Multiple Customizations Multiple observers for the same event Multiple plugins for the same method with execution order

When to Use Observers

  • Use observers when you need to execute code in response to a system event.
  • Great for adding global functionality that doesn’t require modifying method execution.
  • Ideal for broad actions such as logging events, sending notifications, or dispatching custom functionality during the checkout process.

When to Use Plugins

  • Plugins are the go-to choice for fine-tuning the behavior of specific methods.
  • Use them when you need to modify the input or output of a function.
  • Best suited for scenarios where core Magento functionality needs modification at the method level without rewriting the entire class.

Which is Better?

It’s not about which is better, but about which is more appropriate for your use case. If you need to listen for an event and perform an action, observers are ideal. However, if you want to modify how specific methods work, plugins offer more flexibility.

In general:

  • Use plugins when you need precise control over method execution.
  • Use observers when you need to react to events that occur within the system or an extension.

Conclusion

Magento 2 offers robust customization options through both observers and plugins. While observers allow you to listen and respond to system events, plugins provide detailed control over individual methods. Depending on your customization needs, choose the appropriate method to ensure your Magento 2 store runs smoothly and efficiently.

If you need more information on how to override Magento 2 core functionality using preferences, plugins, or event observers, check out our previous blog post here.

For any questions or further assistance, feel free to contact us!


Looking for more Magento 2 tips? Check out our other Magento Development Guide.

Updated: