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.
Table of Content
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.
40 Hours of Magento Services. FOR FREE
Try our custom development, optimization, support, and design services. One week, free of charge, no strings attached.
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.