Magento 2: Plugin before/around/after Interaction

Plugins are sorted by sort order first, and then by method prefix.

Example: for method with 3 plugins (PluginA, PluginB, PluginC) with following methods and sortOrder:

  • PluginA (sortOrder = 10)
    • beforeDispatch()
    • afterDispatch()
  • PluginB (sortOrder = 20)
    • beforeDispatch()
    • aroundDispatch()
    • afterDispatch()
  • PluginC (sortOrder = 30):
    • beforeDispatch()
    • aroundDispatch()
    • afterDispatch()

Execution flow should be following:

  • PluginA::beforeDispatch()
  • PluginB::beforeDispatch()
  • PluginB::aroundDispatch()
    • PluginC::beforeDispatch()
    • PluginC::aroundDispatch()
      • Action::dispatch()
    • PluginC::afterDispatch()
  • PluginB::afterDispatch()
  • PluginA::afterDispatch()

From the Magento 2 cookbook:

If there are multiple plugins that extend the same original function, they are executed in the following sequence:

  • the before plugin with the lowest sortOrder
  • the around plugin with the lowest sortOrder
  • other before plugins (from the lowest to highest sortOrder)
  • other around plugins (from the lowest to highest sortOrder)
  • the after plugin with the highest sortOrder
  • other after plugins (from the highest to the lowest sortOrder)