Plugins SortOrder and Limitations in Magento2
In the previous blog, we’ve discussed how to declare plugins and what are the types of plugins.
In this blog, we will focus on plugin sort order and limitations of plugins in Magento2.
Plugin SortOrder
Plugin sort order is used to decide the priority of executions when multiple plugins are listening to the same method. And if more than one plugin is listening to the same method but doesn’t add sort order or maybe the same sort order then the execution will be decided on component load order by the sequence tag of module.xml and area of plugins.
Sort order works in lower to higher when used in before method and higher to lower when works in after methods. Around plugins execute before the before plugin when around plugin have lowest sort order then before plugin.
Let’s take an example to understand this:-
Order to execute plugins -
Before plugins
Around plugins chaining
After plugins
- Before plugin with the lowest sort order executes first,
Then the around plugin with the lowest sort order,
Then before plugin from lowest to highest,
And same with the around plugin,
After completing the chain of before and around plugin executions,
After plugins execute as highest to lowest sort order.
In the above process plugins will be executed like :-
Plugin1 : beforeMethod()
Because it has the lowest sort order in before plugin.
Plugin2 :beforeMethod()
After the Plugin1, Plugin2 before method has lowest sort order.
Plugin2: aroundMethod()
Plugin2 around method has sortorder 20 which is lowest from Plugin3 before method so this method will execute first.
Plugin3 : beforeMethod()
Executes as lowest to highest sort order in before plugins.
Plugin3 : aroundMethod()
Plugin3 around method as lowest to highest sort order in around methods.
If now aroundMethod is calling the callable method then the original callable method will be executed first and if aroundMethod is not calling the callable then after plugins will execute as highest to lowest sort order.
Action : OriginalMethod() (If callable exist)
Else
Plugin3 : afterMethod()
Because afterMethods executes as highest to lowest sort order so Plugin3 has highest sort order.
Plugin2 : afterMethod()
Execute as highest to lowest sort order in after plugins.
Plugin1 : afterMethod()
Execute as highest to lowest sort order in after plugins.
Plugin Limitations
Plugins cannot be used on following :-
Final methods
Final classes
Non-public methods
Class methods (such as static methods)
__construct
Virtual types
Objects that are instantiated before Magento\Framework\Interception is bootstrapped
That’s all! I hope this tutorial helps you to understand plugin sortorder and limitations well.
Comments
Post a Comment