Home » Magento, Magento 22 August 2016

Magento 2: Before & After Method Observer using Plugin

Magento 2 provides a new feature called Plugin or Interceptor that is used to run some code before/after/around any function call of any public class. Hence, with the help of Plugins, we can change the behavior of class method without making any changes in the code of the class itself. This also avoids conflicts with other modules.

Let’s suppose your module is named YourCompany_YourModule.

The plugin class has to be declared in etc/di.xml of your module. Here is the code:



type’s name = class whose methods are to be observed
plugin’s name = random plugin name
plugin’s type = name of plugin’s class (YourCompany\YourModule\Plugin\Plugin)
plugin’s sortOrder = the order of the plugin to be called
plugin’s disabled = enable/disable plugin, default value is false.

We can add before, after, and around methods to modify the core class functions. For example, if there is a “Save” function in the core class then in the plugin class we can have beforeSave, afterSave and aroundSave method.

beforeMethod = contains code to run before the observed Method
afterMethod = contains code to run after the observed Method
aroundMethod = contains code to run both before and after the observed Method

“observed method” means the function present in the Core class which we want to modify through our Plugin class

In the above di.xml file, we have defined that we are going to observe methods of class Magento\Checkout\Model\Cart in our plugin class YourCompany\YourModule\Plugin\CartPlugin.

In this example, we will be observing a function named addProduct of the core Cart class.

For this example,

If you want to run some code before the addProduct method (adding product to cart), then you will have to create a method named beforeAddProduct in your Plugin class.

Similarly, if you want to do something after adding product to cart, then you will have to create a new function named afterAddProduct in your Plugin class.

And, there is another method named ‘around’. This allows you to execute some code both before and after the observed method is called. For this, you will have to add a new function named aroundAddProduct in your Plugin class.

Here is the CartPlugin class.


Read more about Magento 2 plugins in the official doc: Magento 2 Plugins

Hope this helps. Thanks.

php magento mukesh chapagain

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed