Rewriting Magento 2 classes vs Plugins
The obvious reason to use a rewrite instead of a plugin is when you need to override a private, protected or final methods.
But also consider the following scenarios.
1st scenario (absolute sort order):
Rewrites can be useful when you need your code to be run before plugins.
I know you can do it by setting the plugin sortOrder
, but you cannot be sure your code will always be the first when someone (not you) is going to install 3rd party components.
2nd scenario (exclude code):
If you need to exclude or rewrite just a piece of code in a method, a plugin could be a sub-optimal way.
I know you can use an around
plugin and avoid calling the proceed
, but this could break other plugins in the stack.
3rd scenario (code style):
You should use rewrites when you need to rewrite a behaviour, plugins should be used to modify the output or run code before/after.
A plugin, should always run the original code to avoid breaking other modules.
My conclusion:
If you can consider a core method as a black box with an input and one output and you are agnostic about its internal mechanisms, then a plugin could be the best option.
If you need to change an internal behavior, a rewrite could be the best option.
Great question, I asked myself the same thing the other day and here's what I came up with:
- First, plugins cannot be used for final methods, final classes and classes created without dependency injection I reckon that's a very specific case but that's one case where you can't use plugins
- Second, you need to keep in mind the definition of a plugin. It is used to work on a method level whereas preferences are used to work on the whole class level. It is not obvious for everyone so it's good to keep that in mind.
- Finally, and I reckon that's the most important, it seems like plugins can only be used to extend the behavior of any public method within a Magento class. Thus it seems like you cannot use plugins with protected/private methods.
Source: Magento U Fundamental Course