Plugins (Interceptors) in Magento 2

  • Introduction
  • Understanding Magento 2 Interceptor
  • Benefits of Using Interceptors
  • How to Create an Interceptor in Magento 2
  • Example: Modifying Product Price Calculation
  • Conclusion

Introduction

Magento 2 is a powerful e-commerce platform known for its flexibility and extensibility. One of the key features that enables this flexibility is the concept of interceptors. In this article, we will explore the Magento 2 plugin called “Interceptor,” its role in modifying the behavior of Magento classes, and provide coding examples to demonstrate its usage.

Understanding Magento 2 Interceptor

In Magento 2, an interceptor is a plugin that allows you to modify the behavior of public methods in a Magento class. It works by intercepting the method call, executing custom code before, after, or around the original method, and then returning the modified result. Interceptors provide a way to extend the functionality of Magento classes without modifying their core code.

Benefits of Using Interceptors

Utilizing interceptors in your Magento 2 store offers several benefits:

    Modularity: Interceptors follow a modular approach, allowing you to add or remove them without modifying the core codebase. This makes it easier to maintain and upgrade your Magento installation.

    Customization: Interceptors enable you to customize the behavior of Magento classes to meet specific business requirements. You can add additional functionality, modify input parameters, validate data, or perform any other necessary actions.

    Code Separation: With interceptors, you can keep your customizations separate from the original Magento code. This ensures cleaner code and makes it easier to manage and understand your modifications.

    Compatibility: Interceptors are designed to work seamlessly with Magento’s dependency injection system, ensuring compatibility with other extensions and customizations.

    Declaring a plugin

    The di.xml file in your module declares a plugin for a class object:

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

    You must specify these elements:

    • type name. A class or interface which the plugin observes.
    • plugin name. An arbitrary plugin name that identifies a plugin. Also used to merge the configurations for the plugin.
    • 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\<ClassName>.

    The following elements are optional:

    • plugin sortOrder. Plugins that call the same method run them using this order.
    • plugin disabled. To disable a plugin, set this element to true. The default value is false.

    As the following example, we will edit app\code\Vendor\Module\etc\di.xml, you need to insert the snippet:

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
       <type name="Vendor\Module\Controller\Index\Example"> <plugin name="Vendor_Module_Plugin" type="Vendor\Module\Plugin\ExamplePlugin" sortOrder="10" disabled="false" /> 
       </type> 
    </config>

    For example, the following code define type name, we created ExamplePlugin.php file at app/code/Vendor/Module/Controller/Index

    <?php namespace Vendor\Module\Controller\Index; 
    
    class ExamplePlugin extends \Magento\Framework\App\Action\Action {
    
     protected $title;
    
     public function execute() {
       echo $this->setTitle('Welcome');
       echo $this->getTitle(); 
    }
     public function setTitle($title)
     {  return $this->title = $title; }
        public function getTitle() 
    { return $this->title; 
      } 
    }

    Contents would be:With plugin name, we created Example.php file at app/code/Vendor/Module/Plugin/Contents would be:

    <?php namespace Vendor\Module\Plugin; 
    
      class DemoPlugin{ 
    }
    

    How to Create Interceptors in Magento 2

    Creating interceptors involves a few essential steps. Let’s outline the process:

    1. Identify the Target Method

    Determine the Magento class and method that you want to intercept. It can be any public method within a Magento class.

    2. Create a di.xml File

    In your custom module’s etc directory, create a di.xml file. This file is used to configure your interceptor.

    3. Implement the Interceptor Class

    Create a PHP class that implements your interceptor logic. Depending on the type of interceptor, implement the before, after, or around method.

    4. Configure the Interceptor

    In the di.xml file, specify the interceptor class and the target class and method you want to intercept.

    5. Test and Verify

    Test your interceptor by invoking the target method and ensuring that your custom code executes as expected.

    Three Types of Plugins: Before, After, and Around

    Magento 2 interceptors come in three flavors: “before,” “after,” and “around.” Let’s explore each type:

    1. Before Plugin

    Before interceptors execute custom code before the original method is invoked. They allow you to modify method parameters, perform validations, or execute any necessary actions to prepare for the original method’s execution.

    Example :-

    namespace Lokesh\Module\Plugin;
    
    class BeforePriceCalculation
    {
    public function beforeGetPrice(\Magento\Catalog\Model\Product $product)
    {
    $discount = $this->calculateDiscount($product->getPrice());
    $product->setPrice($product->getPrice() - $discount);
    
    private function calculateDiscount($price)
    {
    // Custom discount calculation logic
    // Example: Apply a 10% discount
    return $price * 0.1;
      } 
     }
    }

    2. After Plugin

    After interceptors execute custom code after the original method has been invoked. They enable you to modify the method’s return value, perform additional operations based on the result, or log relevant information for debugging or analytics purposes.

    Example:-

    namespace Lokesh\Module\Plugin;
    
    class AfterPriceCalculation
    {
    public function afterGetPrice(\Magento\Catalog\Model\Product $product, $result)
    {
    // Apply additional adjustments
    $adjustedPrice = $result + $this->calculateAdjustment($result);
    return $adjustedPrice;
    } 
    
    private function calculateAdjustment($price)
    {
    // Custom adjustment calculation logic
    // Example: Add $5 to the price
    return 5;
     }
    }

    3. Around Plugin

    Around interceptors execute custom code both before and after the original method. They provide the most flexibility as they allow you to completely replace the original method, modify its parameters, control its execution flow, and handle the return value.

    Example:-

    namespace Lokesh\Module\Plugin; 
    
    class AroundPriceCalculation
    {
    
    public function aroundGetPrice(
    \Magento\Catalog\Model\Product $product,
    \Closure $proceed
    ) {
    // Modify the price calculation logic here
    $modifiedPrice = $this->customPriceCalculation($product);
    return $modifiedPrice;
    }
    
    private function customPriceCalculation($product)
    {
    // Custom price calculation logic
    // Example: Multiply the price by 1.5
    $price = $product->getPrice();
    $modifiedPrice = $price * 1.5;
    
    return $modifiedPrice;
      }
    }

    Conclusion

    Interceptors are powerful tools in Magento 2 that allow you to modify the behavior of core classes without directly modifying their code. By creating interceptors, you can customize Magento’s functionality to meet specific business requirements, ensuring a tailored e-commerce experience for your customers.

    With the coding example provided, you now have a solid foundation for creating your own interceptors and implementing custom logic in Magento 2.

    For more – Adobe offical

    Thank you for reading my Article! Feel free to share your thoughts or ask any questions in the comments section below and spread the word by sharing. Your engagement is appreciated!

    Leave a reply

    Your email address will not be published. Required fields are marked *

    Cookies Notice

    Our website use cookies. If you continue to use this site we will assume that you are happy with this.