A Complete Guide On Magento 2 Plugin

magento 2 plugin

An interceptor or a Plugin is a new concept introduced in Magento 2 updated version, while in Magento 1 you need to implement different classes and methods, you would have to rewrite a class for customization. Though, this was a very powerful method to customize but with a cost of flexibility, because no two modules could rewrite the same class. And on the other hand, rewriting created a lot of instability in Magento 1. That is why, Magento 2 created a new customization method to solve this issue, which is plugin or interceptor. 

A module, or interceptor, is a totally different idea that was presented in Magento 2. In Magento 1, to tweak various classes and techniques, you would need to revise a class. This was an extremely strong way for the customization however with an expense of adaptability as no two modules could rework a similar class. Revise clashes made a ton of precariousness in the Magento 1 stage.

 

Why To Use Plugin/Interceptor? 

  1. Plugin overcomes the issue of the Rewriting system you may have faced in Magento 1.
  2. Through the plugins we can customize the same method in various modules. 
  3. You can prevent collisions between plugins by using the sort order attribute of the plugin. It can be called sequentially according to a sort order, so it does not conflict with other plugin classes. 
  4. You can modify the plugins according to your usages.
  5. You can also modify the arguments of any method call that is used on an object manager controlled object. 

 

Magento 2 Plugin’s Restrictions 

Plugins cannot be used with any of the following:

  • Final methods
  • Final classes
  • Non-public methods
  • Static methods
  • __construct
  • Virtual types
  • Objects that are actualize before launching 

 

Some Magento 2 Plugins And Its Advantages

  1. Magento 2 Delivery Date & Time Extension: Will help you to record and maintain the delivery date and time accurately. 
  2. Advanced GeoIP Redirect: Will help you to reach out to the targeted audience overseas. 
  3. Split Order On Checkout Pro: Will help you to manage the order hassle freely. 
  4. Facebook Feed Magento 2 Extension: Will help you to manage your social media promotions and inquiries. 
  5. Magento 2 Blog Extension: Will help you to boost the engagement and organic traffic on your web store or mobile application. 

 

Types Of Plugin In Magento 2 

In Magento 2 we can create and use three types of Plugin, all three are as follows:

  • Before Listener Plugin 

Whenever we want to change the arguments of the actual method or want to add some value before an actual method, we can use the Before Listener Plugin method. Before Listener in other words known as adding the prefix ‘before’ to the method name and setting the first letter of the actual method to capital. 

Prototype: beforeMethodname()

Example: beforeAddProduct()

Original Method: public function addProduct(<ARGUMENTS>) 

Plugin Method: public function beforeAddProduct(<ARGUMENTS>)

 

  • After Listener Plugin 

If we want to change values returned by an original method or want to add some behavior after an original method, then you can use After Listeners. After listener in other words known as adding prefix ‘after’ to the method name and setting first letter of actual method to capital. 

Prototype: afterMethodname()

Example: afterGetName()

Original Method: public function getName(<ARGUMENTS>)
Plugin Method: public function afterGetName(<ARGUMENTS>)

 

  • In Between Listener Plugin  

In Between Listener plugin method is also known as the Around method defined such that their code is run both before and after the observed method. This method allows you to completely override. After Plugin is used for changing both the arguments and returned values of an actual method or adding some behavior before and after an actual method is called. Around listener is called by adding the prefix ‘around’ to the method name and setting the first letter of the original method to capital. 

Prototype: aroundMthodname()

Example: aroundAddProduct()

Original Method: public function addProduct(<ARGUMENTS>)

Plugin Method: public function aroundAddProduct(<ARGUMENTS>)

 

How To Create Magento 2 Plugin/Interceptor? 

Step 1: Declaration of plugin

To use Plugins, first of all, we have to define it in di.xml.

<config>

      <type name=”{ObservedType}”>

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

      </type>

</config> 

 

Explanation

Required elements:

These three elements are required.

plugin type:The name of a plugin’s class or its virtual type. Use the following naming convention when you specify this element: \Vendor\Module\Plugin\<ModelName>Plugin.

Optional elements:

These two elements are optional

plugin sortOrder: The order in which plugins that call the same method are run.

plugin disabled: To disable a plugin, set this element to true. The default value is false.

 

Step 2: Create Plugin Class

Now we will create a plugin class that you define in di.xml as type=”{PluginClassName}” and will use a before, after or around method as per our need. For example;

<?php

namespace Vendor\Module\Plugin;

class ExamplePlugin{

 }

 

Examples Of Plugin<

Let us create some plugin so we can understand all types of plugins

 

1. Before Listener Plugin

In this example we will change qty to 5 so that it always adds 5 quantities of product whenever we add to cart.

Step 1 : create di.xml in etc folder

<?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=”exampleofbefore” type=”Bizspice\Beforelistener\Plugin\Cart” sortOrder=”1″ />

     </type>

</config> 

 

Step 2 : Now create Cart.php in Bizspice\Beforeplugin\Plugin\

<?php

namespace Bizspice\Beforelistener\Plugin;

class Cart

{

    public function beforeAddProduct( \Magento\Checkout\Model\Cart $subject, $productInfo, $requestInfo = null ) {

          $requestInfo[‘qty’] = 5;  

          // increasing quantity to 10

            return array($productInfo, $requestInfo);

     } 

 

2. After Listener Plugin

In this example we will change product price that will reflect everywhere in site including list page , product page ,cart page and in order. 

Step 1 : create di.xml in etc folder

<config>

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

            <plugin name=”change_product” type=” Bizspice\Afterlistener\Plugin\Product ” sortOrder=”1″ />

     </type>

</config> 

 

Step 2 : Now create Product.php in Bizspice\Afterlistener\Plugin\

 

<?php

namespace Bizspice\Afterlistener\Plugin;

class Product 

{

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

        return $result*2;

     } 

}

 

3. Around Listener Plugin

Step 1 : create di.xml in etc folder

 

<config>

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

         <plugin name=”change_cart” type=” Bizspice\Aroundlistener\Plugin\Cartplugin ” sortOrder=”1″ />

    </type>

</config> 

 

Step 2 : Now create Cartplugin.php in Bizspice\Aroundlistener\Plugin\

<?php

namespace Bizspice\Afterlistener\Plugin;

class Cartplugin 

{

     public function aroundAddProduct(\Magento\Checkout\Model\Cart $subject,$proceed){

         // before adding product to cart 

         $productId = (int)$this->request->getParam(‘product’, 0);

         $qty = (int)$this->request->getParam(‘qty’, 1);

         // this will run the core addProduct function

         $returnValue = $proceed(); 

         // below code is executed after product is added to cart

         if ($returnValue)

         {

            // after adding product to cart

         }

          return $returnValue;

      } 

}

 

Conclusion

Creating and using Magento 2 plugins is more complex than you think; but if you want to hire a Magento 2 certified agency then MageCaptain is one the right place you can consider.

LEAVE A REPLY

Please enter your comment!
Please enter your name here