PLUGINS (INTERCEPTORS)
May 22, 2020 by Sujeet Gupta

HISTORY:

  • Magento 1 does not use the plugin concept.
  • Magento 2 introduced the Plugin concept.
  • They are synonyms for platforms like WordPress. But not in Magento!

DEFINITION:

A plugin or interceptor is a class that modifies the behavior of public class functions by intercepting a function call and running code before, after, or around that function call and allows to substitute or extend the behavior of original, public methods for any class or interface.

Simplifying the words,

A plugin or interceptor is a way to insert code dynamically without changing the original class behavior. It allows extending the core functionality without any modification to the core files.

IMPORTANT NOTE:

On Magento 1 allowed to customize different classes and methods by rewriting a class. Powerful, but in this way, no modules could rewrite the same class, and hence, no flexibility. To overcome the rewrite conflicts and instability, Magento 2 comes with inceptors or plugins! And, the post is everything about it from the reasons to use, its restrictions, types, and the method to create a plugin in Magento 2.

WHY SHOULD WE USE PLUGINS IN THE MAGENTO 2:

Minimum confliction among extensions that change the behavior of the same class or method.
Avoid collisions between plugins by using the sort order attribute of the plugin.

The plugin can be called sequentially according to sort order, so conflict with other plugin classes can be avoided.

No issue of rewriting the system.

Customize the same method in different modules.

Ability to modify the return value of any method call that is used on an object manager controlled object.

Ability to modify the arguments of any method call that is used on an object manager controlled object.

THE MAGENTO 2 PLUGINS CAN’T BE USED WITH:

  • Non-public methods.
  • Static methods.
  • __construct.
  • Final Methods.
  • Final classes.
  • Virtual Types.
  • Any class that has at least one final public method.
  • Objects that are instantiated before Magento\Framework\Interception is bootstrapped.

TYPES OF PLUGINS IN MAGENTO 2:

  • Before listener:

Before listeners are used whenever we want to change the arguments of an original method or want to add some behavior before an original method is called.

Before listener is called by adding the prefix ‘before’ to the method name and setting the first letter of original method to capital.

It lets you modify the parameters that will be used.

Syntax: beforeMethodname()

  • After listener:

After listeners are used whenever we want to change the arguments of an original method or want to add some behavior after an original method is called.
It starts running after the observed method is finished.

After a listener is called by adding the prefix ‘after’ to the method name and setting the first letter of the original method to capital.

It let you modify the output.

Responsible for editing the results of an observed method in the right way and must have a return value.

Syntax: afterMethodname().

  • Around listener:

Inceptors run before and after the observed method.

Allows overriding a method.

Used when you want to change both the arguments and the returned values of the observed method or add behavior before and after the observed method is called.

Around listener is called by adding the prefix ‘around’ to the method name and setting the first letter of original method to capital.

It must have a return value.

Syntax: aroundMethodname().

STEPS TO CREATE A PLUGIN IN MAGENTO 2:

Basic Structure:
app/code/Vendor/Namespaces

Step 1
Create registration.php file in app\code\Symphisys\Myplugin.

    <?php
     \Magento\Framework\Component\ComponentRegistrar::register(
      \Magento\Framework\Component\ComponentRegistrar::MODULE,
      Symphisys_Myplugin,
      __DIR__
     );   

Step 2
Create module.xml file in app\code\Symphisys\Myplugin\etc.

    <?xml version="1.0"?>
      <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc
      /module.xsd">
        <module name="Symphisys_Myplugin" setup_version="1.0.0"/>
    </config>

Step 3
Create di.xml file in app\code\Symphisys\Myplugin\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\Controller\Index\Index">
          <plugin name="restrictCartQuantity" 
      type="Symphisys\Myplugin\Plugin\Checkout\Controller
      \RestrictProductQuantity"/>
        </type>
      </config>

Step 4
Create RestrictProductQuantity.php in

    Symphisys\Myplugin\Plugin\Checkout\Controller
  • Before listener:

EX.

  <?php
 
    Namespace Symphisys\Myplugin\Plugin\Checkout\Controller;
 
    class RestrictProductQuantity
    {
        public function beforeExecute( 
  Index $subject,
            \Closure $proceed
        )
        {
            //You required logic
        }
    }

  • After listener:
  <?php
  Namespace Symphisys\Myplugin\Plugin\Checkout\Controller;

  class RestrictProductQuantity
  {
      public function afterExecute(
          Index $subject,
          \Closure $proceed
      )
      {
          //You required logic
      }
  }

  • Around listener:
  <?php
 
  Namespace Symphisys\Myplugin\Plugin\Checkout\Controller;

  class RestrictProductQuantity
  {
      public function aroundExecute(
          Index $subject,
          \Closure $proceed
      )
      {
          //You required logic
      }
  }

NOTE:

  • We will use anyone lister as per our requirement.
  • In their vendor name is Symphisys and Namespaces is Myplugin.