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:
syntax – ‘before’ + MethodName
syntax – ‘after’ + MethodName
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:
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.