Skip to main content

Plugins in Magento2

Plugins in Magento2




Unlike Magento1, Magento2 introduces a whole new concept of Plugins or Interceptor. A plugin or interceptor is used to change the behaviour of the method of any class without affecting the actual class. This is a very powerful way to customize the core classes of Magento2. 


Plugins are one of the customization methods in Magento2. In plugins, there is a design pattern called “Interception” which means “Inserting code dynamically without changing original class behaviour” and this is what plugins exactly do in Magento2. Plugins modify the behaviour of a plugin class function by intercepting a function call and adding code before, after and around that function’s call. 


Plugins are used with public methods only. 


Declaring Plugins


To declare plugins in Magento2, we have to create di.xml according to the specific area. 

Create di.xml inside Vendor/Module/etc for global.  


<config>

   <type name="{ObservedType}">

     <plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="false"/>

   </type>

</config>



Here, 

ObservedType Is a class for which we are creating a plugin. 

pluginName Is a name for the plugin. 

PluginClassName Is a plugin class which we are creating for customizations. 

sortOrder is used to prevent the conflicts between plugins of the same method. Plugins that calls the same method will be called based on a sortorder defined here. 

disable is used to disable the plugin. 


This is how we can declare our plugin class. 


Types of Plugins


There are 3 types of plugins in Magento2. 

  1. Before Plugin

  2. Around Plugin

  3. After Plugin

 

Before Plugin


Before plugin is used in Magento2 to change the argument of a function or to change the behaviour of a function before calling the actual function. Before plugins are called before magento calls the original method for which we are creating the before plugin. 


The class name of the before plugin should be like this :- 


beforeClassName


We have to add the prefix “before” and capitalize the first letter of the class name, if we have underscore before the class name then we don’t have to capitalize the first letter. Ex :- before_className. 


Let’s take an example to understand the concept of before plugin. 


Now we are creating a before plugin for addproduct function which is used to add products in the cart in Magento2. As mentioned above we have access to change the argument of the original function in before plugin. So here, we will change the requested quantity argument and will set as 10. This argument is used to get the quantity to add product in the cart but we can change this argument in our before plugin. Now everytime customer will be adding any product to the cart, it will automatically add 10 products together as we have changed the requested quantity argument in before plugin. 


First, Create di.xml inside Vendor/Module/etc


<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

   <type name="Magento\Checkout\Model\Cart">

       <plugin name="beforeplugincart" type="Vendor\Module\Plugin\Cart" sortOrder="1" />

   </type>

</config>

 


Now create a plugin class inside the plugin folder of your module. 

Create Vendor/Module/Plugin/Cart.php


<?php

namespace Vendor\Module\Plugin;

class Cart

{

public function beforeAddProduct(

   \Magento\Checkout\Model\Cart $subject,

   $productInfo,

   $requestInfo = null

){

   $requestInfo['qty'] = 10; // increasing quantity to 5

   return array($productInfo, $requestInfo);

}

}



Here we have changed the argument of targeted class. And this before plugin will be called before calling the original method and after that the original method will be performed according to the argument we have changed in before plugin.




10 products are added to the cart. 


Around plugin


In Magento2, around plugin is used to run your own code before, after and during the execution of the original method. We can change the argument and return value of public methods using around plugin. We can also use it as a replacement of the original function. 


In around plugin we use a parameter called collable class which is used to call the original method. Using around plugin we can run the code both before and after the original method . 


<?php

namespace Vendor\Module\Plugin\Around;

class Plugin

{

   public function aroundGetMessage($subject, callable $proceed, $thing='World', $should_lc=false)

   {

       echo 'Calling' . __METHOD__ . ' -- before',"\n";

       $result = $proceed();

       echo 'Calling' . __METHOD__ . ' -- after',"\n";

       return $result;

   } 

}



This code is to understand the execution of around plugin. 

Here, $proceed is used to call the original method, so before proceed we are adding our own code then we are calling the original method using proceed then again running our own code after proceed. If we do not call proceed then the original method will not be called and the around plugin will be used as a replacement of the original method. When you wrap a method which accepts arguments then you must forward them when you invoke the proceed. 


The around plugin must have a return value. 


After Plugin


After plugin is used to run your own code after the original method call. After plugin is used to change the returned value of an original method. 


Let's take an example of after plugin. 


Now we will create an after plugin for getName method which is used to get the product name of your store, this method returns the name of the products. As mentioned we can change the returned value of the original method using the after plugin so here we’ll change or add something in product name returned value. 


Around plugin is called by adding the “after” prefix to the method name and capitalizing the first letter of the original method. 


First, Create di.xml inside Vendor/Module/etc

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

   <type name="Magento\Catalog\Model\Product">

       <plugin name="productname" type="Vendor\Module\Plugin\Productname" sortOrder="1" />

   </type>

</config>


Create Productname.php inside Vendor/Module/Plugin


<?php

namespace Vendor\Module\Plugin;

class Productname

{

   public function afterGetName(\Magento\Catalog\Model\Product $subject, $result) {

       return "Offer!! ".$result; // Offer!! will add before Product Name

   }

}     

 



We have added the “Offer!!” prefix to the result value of the original method. Now “Offer!!” will be added before all the products names. 






When to use plugins


  • When you want to customize the behaviour of any function without affecting the original class. 

  • When you want to change the argument of a method. 

  • When you want to modify or change the return value of a method. 

  • When you want to customize the same method in different modules. 


That’s it. I hope this tutorial helps you. 


In the next blog, we’ll discuss the restrictions and execution order of plugins in Magento2. 


Comments

Popular posts from this blog

Magento2 CLI

Magento2 CLI  Back after a long break! Starting again with this blog because I found it the most important to understand if we are doing the magento development as magento commands play the most important role here. It really helps us a lot if we know that lĺwhich command we need to run on this action or after any changes.  Let’s start with the basic commands that we use a lot of times during our development.  cache:clean or cache:flush php bin/magento cache:clean Or  php bin/magento  cache:flush Both of these commands are used to clean the cache of Magento2 so that your new changes can be reflected to your store.  Using cache:clean it deletes all the enabled cache of magento2. Disabled caches are not affected with cache:clean but if you are doing cache:flush then it purges all the cache storage of magento wherever its enabled or disabled or it even deletes all the third party cache along with the magento cache.  If you are doing any changes in admin configuration, layout xml file, u

How EAV Model Works in Magento2?

                         How EAV Model Works in Magento2?  EAV Model stands for Entity-Attribute-Value is a very important concept of magento2 to understand how the attributes of entities are stored and works in magento2.  EAV Model is described as :-  Entity - Entity refers to the data items such as customers,orders,catalog,category etc.  Attribute - Attributes of the entities like price is an attribute of the product(entity) is referred here is an attribute. Value - A value of the attribute as $20 is a value for price attribute is referred here is a value.  Use of EAV Model EAV(Entity-Attribute-Value) is used to create new attributes of entities such as products, categories etc. With the use of eav models we don’t need to change the structure of the core tables of attributes thus it increases the scalability of the system.  Let’s have a look at how eav works in Magento2 -  Eav model used many several tables to store the data of the entity attributes. The top most table for the e