Magento2 – Plugin vs Observer

event-observermagento2plugin

In Magento 2, what are the pros and cons of using a plugin vs an observer to achieve something?

I understand that observers are subscribed to events whereas plugins can jump in before and/or after a public method being called on a Magento class, but surely they're coming very close to crossing paths now?

Best Answer

Plugins are omnipresent since it is possible to modify/replace the behavior of any public method in the system. Customizations should be done using plugins for public methods/classes marked with @api annotation (stable public API) whenever possible. Such approach guarantees that customization will stay functional after new Magento releases. In addition to before/after plugins mentioned in the question, it is possible to create around plugins to substitute original behavior.

On the other hand, observers are legacy extension mechanism inherited from Magento 1, it is pretty limited and should be avoided if possible. However, unlike plugins, they may provide extension points inside protected/private methods.

Related Topic