Image via Bitbull
Plugins are a brand-new way to extend Magento 2 and, as often happens according to the law of the instrument, if all we have is a hammer, everything looks like a nail.
This article will walk through the main differences between the good old events and plugins, and when it still makes sense to use events instead of plugins to hook our customizations.
Soft vs. hard dependencies
The very first difference is that events are soft dependencies while plugins are hard dependencies.
Let me explain. If our observer depends on an event triggered by a module that is disabled, our functionality stops working gracefully. In other words, nothing apparently breaks.
Of course, since our observer is not called, something won’t work as expected, but the platform doesn’t throw an exception, and the storefront navigation won’t be affected.
This behavior makes an event a soft dependency.
Conversely, if a plugin depends on a class that could not be found by the system, a runtime exception will be thrown, revealing to the world that something doesn’t work as expected.
This behavior makes a plugin a hard dependency.
It’s important to know this difference because it can guide us in deciding whether to use an event or a plugin to hook our customizations.
Let’s make a couple of examples; they are trivial, but it’s just to give an idea.
If we need to determine whether to show a notice in the cart page that tells us the amount we need to reach to have free shipping, we may use an event (e.g., sales_quote_collect_totals_after). If the event is not triggered, we don’t want the storefront to crash just because of a missing notice, albeit an important one. Thus an event could be the right choice.
If we need to prevent users from placing an order unless the quote reaches a certain margin, we could choose to use a plugin. If the plugin breaks, the storefront will break as well, and that guarantees us that the users won’t be able to place an order. It’s not a good thing to have a broken storefront, but it can be worse for merchants to receive orders at a loss. Thus, a plugin could be a better choice.