What Is Plugin In Magento2?

By, Abhiruchi Paygude
16th August 2022

Magento 2 Plugin is a method where you can extend the functionality of any PHP public method where it performs the code Before, after and around.

Let’s take an example, suppose the original Magento function returns the string value where you return the name doctors and you want to add  ‘Dr.’  after you get a name. For this customization, we can use a plugin which will take the name from the original method and will the prefix (Here Dr.) to it based on conditions.

Magento plugin firstly checks the sequence and gets executed with specific sortOrder.

The plugin is responsible for changing the result of the original method.

Three ways of using the plugin:

  • Before:  In the before method plugin gets executed  Before the original method in Magento.

   syntax –  ‘before’ + MethodName

  • After: In the after method original method gets executed and then the plugin performs its functionality.

 syntax –  ‘after’ + MethodName

  • Around: In the around method code gets executed before and after method the original method.

 syntax –  around + MethodName

Avoid using around method plugins when they are not required because they increase stack traces and affect performance. The only use case for around method plugins is when the execution of all further plugins and original methods need termination. Use after method plugins if you require arguments for replacing or altering function results.

Changes in the di.xml file: In the di.xml file, we need to add given details as shown in the image below such as the plugin name, the path of the original file and the path of the plugin for the mapping. Here sortOrder is also important if we have two plugins then based on sortorder it will get executed. Without declaring the function in this file, the plugin will not perform its function. 

 Limitations while using a plugin: 

  1. Final methods.
  2. Final class.
  3. Non–public methods.
  4. Class methods are like static methods.
  5. __construct
  6. Virtual types. 

How to disable the plugin: In Magento2 we can disable the plugin when it is not needed. We can use the  ‘disabled’ parameter and set the parameter value equal to ‘true’. We have to make these changes in the di.xml file. Remember you have to provide the same path while calling and disabling the plugin in the di.xml file.

That’s some beginner’s information regarding the Magento 2 plugin. Hope this blog is helpful for you please do share your review. 

Thank you!

Coditron Technologies


Corporate Office : Greens Center, Thergaon Pune 411033

Operation Office: USA: PO Box # 582973 ElkGrove CA 95758