Table of Content

Magento 2 Plugins and Observers (Updated for 2024)

Plugins vs Observers in Magento

Even though both plugins and observers have been around for quite some time, many Magento developers don't really understand the distinction between the two and which one you should use in different situations.

Over the years, we've optimized a lot of third-party extensions and customizations, fixing the mistakes of inexperienced developers and the consequences of poor development choices and methods. We know what it means to neglect the research, whether to use plugins or observers for what you’re trying to build.

So, in this blog post, we'll take a look at plugins, observers, and preferences, compare them with one another, and showcase situations in which these development tools work the best.

A Question of Preference in Magento 2

Some extension developers use preferences and don't make a big deal out of it. But the way Magento handles user preferences doesn't allow us to utilize them as a good replacement.

Preferences don't offer enough reliability in Magento. Let's say two distinct extensions use preferences to set the same value. Because of the way Magento loads extensions, it will rewrite the value with the preference that was loaded last.

This means if two different extensions use the same preference to modify something, the preference that loads last will override everyone else's changes. This conflict will lead to huge bugs in extensions that are loaded first, which is, of course, unacceptable.

But if you use redefining too often, expect extensive compatibility testing when you need to to get a newer Magento version. This happens because when something gets added to the constructor, the affected class that gets redefined will also require you to add the same code to your own class.

But changing the construct is only one of the reasons Magento acts up. Another factor is adding new features to the store. In this case, the slowdown happens because when Magento gets new features, you have to port them over to your rewritten code. In addition, your code can stop working from the slightest change in the class you’ve redefined.

Execute the command bin/magento setup:di:compile in order to check your code for this issue. Nevertheless, it won't free you from the task of analyzing the cause of this change and making the code compatible with the new changes in the redefined file.

You could use preferences to customize the Magento store if you’re the only one who creates customizations for the store and you’re sure they won't conflict with one another. In any other case, we strongly advise against using preferences for customizations.

Are Event Observers Still Relevant?

When we remove preferences from the equation, what we are left with are and . Observers used to be one of the main means of adding changes to the code logic, but today, this is the prerogative of dependency injections and plugins. Event observers are legacy elements from the Magento 1 era, which are quite limited in what they can do.

Speaking from our own experience, a lot of use observers for their extensions but don't really implement them properly. For example, an extension will use an event observer to make checkout faster.

A poorly built observer can affect the entire store's performance. For example, if you hook up the observer to the model_load_after event and make a badly optimized function there, the store can become punishingly slow. That's why we've recommended removing unnecessary plugins and observers in our complete guide on

Observers are not without their uses, though. Even if their best years are now behind them, they still offer a decent number of applications. One prominent example would be creating extension points inside private or protected Magento methods.

Observers are also useful when you need to log something specific, clean the cache, or send a piece of data to another system. They are 100% fit for tracking changes/creation/removal/initialization of specific models inherited from \Magento\Framework\Model\AbstractModel.

One crucial point, though. Let's say we need to save every changing model ID into a log file. If you wanted to use a plugin, you'd have to create one for every model in the system that uses AbstractModel inheritance.

At the same time, you can't attach this plugin directly to the AbstractModel since this class has a regular save function. The function works fine for any model that triggers the model_save_after event used to track the changes in every inheritance that calls on this function.

Observers are extremely useful if you need to find a workaround for the limitations that plugins have. If you attach a plugin to the parent class from which many other classes are inherited, it won’t work. But if the parent class generates an event, then it’ll be possible to perform actions with all entities that are inherited from that event.

Plugins Lead the Way

Plugins are more versatile than observers. Plugins can change the behavior of public methods in Magento (except for virtual and final classes, final, static, non-public methods, constructors, and objects instantiated before bootstrapping Magento\Framework\Interception). 

Compared to event observers, plugins can function anywhere in the system. They can be used to change or override public methods in Magento. Plugins are a valuable tool in custom development. For example, they aren’t affected by new Magento patches.

With stable public API (bearing the @api mark), developers can write plugin-based code resistant to new Magento updates that offers all three methods (before, after, and around) to overwrite the original Magento 2 behavior.

Plugins are also called interceptors because they can intercept the function before, during, and after the call. See, the thing is, you can change almost any function with a plugin:

  • with Before plugins, developers can edit input arguments;
  • with After plugins, they can change the result of the function;
  • and using Around plugins, they can completely change the function's logic.

In plain English, this means that plugins don't conflict with one another. They are always called one by one according to a pre-sorted sequence, which reduces mutual conflicts. Even more:

  • used throughout the platform, plugins can be implemented for any public function;
  • they’re great for a Magento extension that needs to intercept and change public method behavior;
  • when too many plugins are used around the call, they increase stack traces and reduce site performance.

Plugins vs. Observers: What's the Right Tool for the Job?

Magento 1 didn't generally leave developers with a lot of options. If they needed to change the behavior of the original code, they either had to implement observers to listen to certain events or deal with a confusing mess of preferences that could screw with each others' values if the developer wasn't careful enough.

But now, the time of event observers is long gone. Observers are stuck in the M1 era. They’re mostly used as a part of legacy code or in narrow applications in Magento eCommerce website development.

Event observers have disadvantages:

  • observers are slower than plugins because Magento creates at least three objects upon the trigger event;
  • observers offer less flexibility when you need to introduce platform-wide features;
  • event observers have critical limitations since they MUST NOT change the objects they influence.

Bear in mind that sometimes event observers can be useful even in Magento 2 development. Same as in M1, setting up observers can come in handy when you want to implement store-wide features, such as a reward system and bonus points for purchases.

But even then, you are better off using plugins to get the job done. Event observers can be also used separately for frontend and adminhtml (with events.xml file designating their field of application).

Magento 2 Plugin vs. Observer: What to Use, When to Use

Core Magento 2 also has a lot of places where event observers play a prominent role in changing the application's logic. The sheer number of places where observers work inside Magento means that it would be complicated to get rid of them any time soon. There's no doubt in the developer community that observers will eventually fade out of favor. But it’ll only happen when Magento 2 completely abandons inheritance in favor of composition, which is not a matter of the near future.

We've created a mini-guide on how to choose the optimal tool for your task (ranked from most suited to less suited):

  • Use plugins with @api methods over simple plugins. @api methods won’t get changed often by the Magento core dev team and thus are more reliable and future-proof;
  • Event observers will remain your second-best choice, especially if you’re well-acquainted with them from the M1 dev times;
  • Non@api plugins should be used last. They offer less stability than event observers and don't have the advantages of @api plugins.

Magento 2 Observer vs. Plugin: Conclusion

To run the business effectively, you need not only to manage the store but also to add new functionality to meet the customers' needs. That's where you need to understand the differences between a Magento 2 preference vs. plugin vs. observer.

When talking about plugins, observers, and preference usage, the main difference between them lies in the way they interact with and modify the Magento system. Plugins intercept and modify the behavior of specific methods without altering the original code. Preferences support custom implementations, completely overriding existing classes or methods. You get a new functionality in place of the default Magento behavior.

Observers, on the other hand, don't change the core functions themselves. They react to specific events that occur within the application and perform the needed task.

We've taken a deep dive into the tasks these development tools perform. Now, it's your turn to choose how you expect your Magento store to operate. Do you still have trouble upgrading your third-party extensions from observers to plugins? Do you want to boost the store speed or make it more reliable?

Being a , Onilab can help you move faster in the dynamic eCommerce environment and upgrade your Magento extensions with proper plugins and preference implementation. Write to us to start your faster eCommerce journey today.

Related Articles

Magento 2 Migration: The Complete Guide
Alex Husar
Alex Husar, Onilab CTO

Magento 2 Migration: The Complete Guide

29 min
May 26, 2020
How to Run an Internal Magento 2 Audit: Everything You Need to Know
Alex Husar
Alex Husar, Onilab CTO

How to Run an Internal Magento 2 Audit: Everything You Need to Know

12 min
May 28, 2019
Magento 2 Speed Optimization: 32 Effective Fixes (Updated 2024)
Alex Husar
Alex Husar, Onilab CTO

Magento 2 Speed Optimization: 32 Effective Fixes (Updated 2024)

21 min
Jul 6, 2023

Plugins vs. Observers in Magento 2: FAQ

What Is the Difference Between Event Observers and Plugins in Magento 2?

An event in a Magento store is a piece of code telling the system that something has happened. For example, it can alert the application that a customer has placed an order. Observers track these events. Magento 2 gets this signal and initiates a certain activity, say, updates a database.

A plugin aims to extend the platform-wide functionality. For instance, you may change a typical way of organizing a shopping cart page with a plugin and add a gift wrap option. In Magento 2, plugins work as interceptors, allowing you to insert custom code before, after, or around a Magento public method in a Magento class. Note that we talk about only a public function, not final classes or private and static methods.

Why Use Observers in Magento 2?

The role of event observers is to monitor and respond to what's happening within Magento 2. The advantage of this solution is that you don't have to tweak the original code, preventing issues during system updates and simplifying troubleshooting. Suppose you want to add loyalty points to a customer account. Use the observer to track purchases and update rewards accordingly.

What Is the Difference Between a Magento 2 Plugin vs. Preference?

Plugins are all about Magento framework interception. They enable you to modify a specific task Magento is performing, but in a more subtle way compared to a preference. The original method remains untouched; you only slightly tweak the code. And that's among the major differences between a plugin and preference in Magento 2.

A preference calls for deeper code customization. It creates more risks during system updates but allows you to replace the unneeded functionality with a more suitable solution. Preferences are used less frequently due to drawbacks. They’re ideal for extensive modifications where the original functionality needs a complete overhaul. For most of the tasks, plugins are enough to customize the store.

Let’s stay in touch

Subscribe to our newsletter to receive the latest news and updates.