How to use plugins (interceptors) in Magento 2

In Magento 2 version, developers have a new possibility to extend or change the behavior of any public method within a core class through Plugins(Interceptors), that is based on Interceptor design pattern.

Interceptor classes are generated dynamically and can be found in generated/code folder. They extend the original classes but wrap its methods to allow a plugin to be called before, after or instead of a required method.

So there are three types of plugins: before, after and around.

Before plugins

We should use these plugins Magento in order to modify the arguments passed to the original method or add some behavior before the method is called.

Let’s create before plugin. For example, we need to log password changing. We will create a plugin for the changePassword method of Magento\Customer\Model\AccountManagement class.

1. To di.xml add the following code:

We must define required arguments:

  • type name: a class, interface, or virtual type that the plugin observes
  • plugin name: an arbitrary name that identifies the plugin; used to merge the configurations for the plugin
  • plugin type: the name of a plugin class or its virtual type; uses the naming convention <ModelName>\Plugin

The following arguments are optional:

  • plugin sortOrder: the order in which plugins that call the same method are run
  • plugin disabled: set to TRUE to disable a plugin

2. Create MageDirect\Test\Plugin\Model\LogChangePassword class and enter the following:

Notice that we name our method as before{methodName}. If we want after(around) plugin, it should be after{methodName}(around{methodName}).

3. Clean cache:

4. In generated/code/Magento/Customer/Model/AccountManagement/ folder we can see Interceptor class and changePassword method:

All plugins are called in the ___callPlugins method of \Magento\Framework\Interception\Interceptor.

After plugins

After plugins are used whenever we want to change the returned result or add some behavior after the method is called.

Here is an example of after plugin:

And di.xml:

In this example, we have changed the returned value of the getCopyright method.

Around plugins

Around plugins can be used when we want to change both the arguments and the returned values of an original method or add some behavior before and after an original method is called.

Let’s take a look at an example of around plugin, that log info before and after add item to wishlist.

More information

More info in the official documentation:

Still have questions? Ask MageDirect experts about Magento consulting. Develop your business in a fast and efficient way.

Was this article helpful?
Dislike 0
Views: 281
Lilya Gogoleva

Lilya GogolevaMagento Developer

Rate us
Please wait...