magento-2-plugins-vs-observers

Magento 2 Plugins Vs Observers: Which One Is Better?

by Grace Bui

Both Magento 2 plugins and observers have been available for a long time. However, many developers are unaware of the differences between the two and which should be used in which situations.

Over the years, we’ve optimized a number of third-party extensions and customizations where inexperienced developers utilized bad development methodologies rather than researching whether they should use plugins or observers for what they were trying to construct.

So, in this post, we’ll look at Magento 2 plugins, observers, and preferences, compare them and show you how these development tools perform in real-world scenarios.

Magento 2 Plugins Or Observers: A Question of Preference

Some extension developers don’t make a big deal out of user preferences. However, the way Magento handles preferences prevents us from using them as a viable solution.

In Magento, preferences aren’t reliable enough. Let’s imagine preferences are used by two different extensions to set the same value. Magento will replace the value using the preference that was loaded last due to the way Magento loads extensions.

magento-2-plugin

This means that if two extensions utilize the same preference to change something, the preference that loads last will take precedence over the modifications made by the other extensions. This disagreement will result in a slew of defects in the first-loaded extensions, which is obviously undesirable.

If you utilize redefining too frequently, expect extensive compatibility testing the next time you upgrade to a newer Magento version. This occurs because if something is added to the constructor, the impacted class will need you to add the same code to your own class as well.

But changing the structure isn’t the only reason Magento is acting up. Adding new features to the store is another consideration. The slowness occurs in this instance because when Magento receives new features, you must port them over to your rewritten code. Furthermore, even the tiniest change in the class you’ve redefined can cause your code to fail.

Run the bin/magento setup command:

To examine your code for this issue, use di:compile. Even so, it will not relieve you of the responsibility of determining the source of the change and adapting your code to the new modifications in the redefined file.

If you’re the only one that customizes the store and you’re sure they won’t conflict, you might utilize preferences to customize your Magento store. We highly advise avoiding utilizing preferences for customizations in any other circumstance.

Is the Role of Event Observers Still Important?

When preferences are removed from the equation, just observers and plugins remain. Observers used to be one of the most common ways to make changes to the code logic, but dependency injections and plugins now take care of it. Event observers are legacy elements from the Magento 1 period, and their use is severely limited.

From our own experience, many Magento developers employ event observers in their extensions but fail to correctly implement them. An event observer, for example, will be used as an extension to speed up Checkout.

A badly constructed observer can have an impact on the entire store’s performance. If you connect the observer to the model load after the event and write a poorly optimized function there, the store can become excruciatingly slow. We propose deleting unnecessary plugins and event watchers in our entire guide to Magento 2 speed optimization.

However, event watchers aren’t completely useless. Even if their finest years are over, they still have a good number of applications. Creating extension points within private or protected Magento methods is a good example.

magento-2-observer

When you need to log something specific, empty the cache, or communicate a piece of data to another system, observers come in handy. They are ideal for tracking changes to, creation of, removal of, and initialization of specific models derived from MagentoFrameworkModelAbstractModel.

However, there is one vital factor to consider. Let’s imagine we need to keep track of every new model ID in a log file. You’d have to write a plugin for each model in the system that supports AbstractModel inheritance if you wanted to use one.

On the same hand, because the AbstractModel contains a regular save function, you can’t directly attach this plugin to it. The function works for any model that fires the model save after event, which is used to track changes in every inheritance that uses it.

Observers are incredibly beneficial if you need to find a way around a plugin’s limits. It will not function if you attach a plugin to the parent class from which numerous additional classes are inherited. However, if the parent class generates an event, any entities inherited from that event will be able to take action.

Magento 2 Plugins Lead The Way

Observers are less versatile than plugins. Plugins can alter the functionality of any Magento public method (except for virtual and final classes, final, static and non-public methods, constructors, and objects instantiated before bootstrapping Magento\Framework\Interception).

Plugins, unlike event watchers, can operate everywhere in the system. They can be used to modify or override any Magento public method. Plugins are an important part of custom development. New Magento updates, for example, have no effect on them.

Developers can design plugin-based code resistant to new Magento updates and offer all three methods (before, after, and around) to supersede the original Magento 2 behavior when used in conjunction with a stable public API (carrying the @api mark).

Because they can intercept the function before, during, and after the call, plugins are also known as interceptors. You see, with a plugin, you may change practically any function:

Developers can:

  • Edit input arguments with Before plugins
  • Change the function’s result with After plugins 
  • Totally change the logic of the function with Around plugins.

In layman’s terms, this means that plugins don’t interfere with each other. They are usually called one by one in a pre-determined order, which helps to avoid mutual disputes. There’s more:

Plugins are utilized throughout the platform and can be implemented for any public function; they’re useful for extensions that need to intercept and change public method behavior; however, using too many plugins around a call causes stack traces to grow and site performance to suffer.

The Appropriate Tool For The Task

Magento 1 didn’t provide a lot of possibilities for developers. If they wanted to change the behavior of the original code, they had to either construct observers to listen for certain events or deal with a jumble of preferences that could mess with each other’s values if the developer wasn’t cautious.

However, the era of event observers has passed. Observers have been trapped in the M1 period. In M2 development, they’re mainly employed as part of old code or in small apps.

There are some drawbacks to being a spectator at an event:

Because Magento creates at least three objects in response to the trigger event, observers are slower than plugins; observers provide less flexibility when introducing platform-wide functionality, and event observers have key limits in that they MUST NOT modify the objects they impact.

magento-extensions

Keep in mind that even with Magento 2 development, event observers can be valuable. Setting up observers, just as in M1, can be useful when you wish to implement store-wide features like a reward system or bonus points for sales.

Even so, you’re better off relying on plugins to complete the task. Separate event observers can be utilized for the frontend and adminhtml (with events.xml file designating their field of application).

When To Use What And When To Use

There are numerous locations in Magento 2’s core where event observers play a significant role in modifying the application’s behavior. The sheer number of areas where observers work inside Magento means that getting rid of them anytime soon will be incredibly tough.

Observers will, without a doubt, fall out of favor in the developer community at some point. But that won’t happen until M2 totally abandons inheritance in favor of composition, which isn’t going to happen anytime soon.

We’ve put up a quick guide to help you pick the best tool for the job (ordered from best to worst):

  • Plugins using @api methods should be preferred over simple plugins. The Magento core dev team will not frequently update @api methods, making them more reliable and future-proof.
  • Your second-best option will be event watchers, especially if you know them from the M1 development period.
  • Plugins that aren’t @api should be utilized last. They are less reliable than event observers and lack the benefits of @api plugins.

Conclusion

Have you been unable to convert your third-party extensions from observers to plugins? Do you want to increase the pace of your store or make it more reliable? You can visit our BSS Extension now to know more.

You can also check >>> Accelerate Your Promotion Strategies: 05 BEST Magento 2 Plugins for more information. 

BSS Commerce is one of the leading Magento extension providers and web development services in the world. With experienced and certified Magento developers, we commit to bringing high-quality products and services to optimize your business effectively.

Furthermore, we offer FREE Installation – FREE 1-year Support and FREE Lifetime Update for every Magento extension.

CONTACT NOW to let us know your problems. We are willing to support you every time.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.