The sortOrder property for plugins in Magento 2 determines when to call them (before, after, or around a method), on condition more than one plugin is configured for the same method.

<config>
    <type name="{ObservedType}">
      <plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="false" />
    </type>
</config>

Prioritizing rules are as follows:

  • Before executing the original method, Magento will run before plugins from the smallest to the biggest value in sortOrder.
  • The part of the plugin around code will also be executed from the smallest to the biggest value before calling the original method (callable).
  • The after plugin is called from the biggest to the smallest after calling the original method.

Example:

Suppose there are three plugin classes (Plugin10, Plugin20, Plugin30). Each plugin class has before, after and around methods for the same method. sortOrder looks as follows for each of them:

Plugin10 - 10
Plugin20 - 20
Plugin30 - 30

The plugins and the original method will be called in the following order:

1 Plugin10::beforeMethod
2    Plugin10::aroundMethod // first part of the code,that is called before callable
3        Plugin20::beforeMethod
4            Plugin20::aroundMethod // before executing callable
5                Plugin30::beforeMethod
6                    Plugin30::aroundMethod // before executing callable
7                        Class:method
8                    Plugin30::aroundMethod // after executing callable
9               Plugin30::afterMethod
10            Plugin20::aroundMethod // after executing callable
11        Plugin20::afterMethod
12    Plugin10::aroundMethod // after executing callable
13 Plugin10::afterMethod