Magento 2: Plugin vs Observer
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.
According to Magento technical guide (https://devdocs.magento.com/guides/v2.1/coding-standards/technical-guidelines.html#14-events): All values (including objects) passed to an event MUST NOT be modified in the event observer. Instead, plugins SHOULD BE used for modifying the input or output of a function.
For me the main difference between plugins and observers is:
- Plugins can modify only public methods while observers can modify private, protected as well.
- There is sort order for plugins but there is no sort order for observers.
- You can add observer only to the events that are already dispatched in Magento. Plugins are more flexible here.