Plugin(Interceptors)

Blog
Spread the love

In contrast to Magento 1, which focuses on rewriting the entire classes for customization, Magento 2 Introduces feature interceptors or plugins, that enhance flexibility and stability of core functionalities without compromising the system integrity.

“A plugin or interceptor in Magento 2 is a versatile approach that modifies the behavior of public methods without altering the original class behavior or core files. It operates by intercepting function calls within a class and executing custom code before, after, or around these calls. This clever approach prevents conflicts and ensures smooth execution of code.”

Declaring a plugin

The di.xml file under the etc directory in your module declares a plugin for a class object. like :

app\code\Vendor\Module\etc\di.xml

Where,

type name: Name of the class or interface on which we are going to apply the plugin.

plugin name: An arbitrary plugin name as an identifier of a plugin.

plugin type: Name of Pluginin class or virtual type. that must follow the naming convention like

app\code \Vendor\Module\Plugin\

Additionally, we may also use the following to make it more functional and intentional

plugin sortOrder: When multiple plugins target the same method, this ‘sort order’ determines the sequence in which they execute. It ensures precise control and sequencing of your enhancements.

plugin disabled: If you wish to temporarily disable a plugin, you can flip this switch to ‘on’ to set its value as true. It’s a handy way to fine-tune your store’s behavior without removing the plugin entirely.

Defining a Plugin

A plugin extends or changes how a public method works by adding code before, after, or around it.

Plugin Method Naming Convention

In Magento, it’s recommended to start the plugin method name with a capital letter, followed by ‘before,’ ‘around,’ or ‘after’ to specify when it should be executed. For example, to create a plugin for the setEmail method of some class:

In the plugin class, the setEmail method may have one of the following names:

beforeSetEmail

aroundSetEmail

afterSetEmail

If the first letter in the name of the class method name for which you want to create a plugin is the underscore character, then you do not need to capitalize it in the plugin class. Let’s do the real implementation of using apply these plugins.

Before Listener

Before listeners are used whenever we need to alter the arguments of an original method or need to add some behavior just before an original method is called. Before methods kick off the action inside another method, and they need to have the same name as that method, but with ‘before’ at the start.
You create a before listener by naming it with ‘before’ at the start and capitalizing the first letter of the original method’s name.

Example of Before Listener

Step:01 Create di.xml file under app\code\Bluethinkinc\CustomModule\etc\di.xml

Step:02 Create PluginClass for BeforeListener at app\code\Bluethinkinc\CustomModule\Plugin\BluethinkCartPlugin

The method beforeAddProduct is the actual plugin method. It is executed before the original addProduct method. The parameters are:

$subject: An instance of the original class (Cart in this case).

$productInfo: The original first parameter of the addProduct method.

$requestInfo: An optional parameter that is the original second parameter of the addProduct method.

In short, This plugin is designed to intercept calls to the addProduct method of the Cart class and
modify the quantity in the request information before the original method is executed.

After Listener

After methods in Magento 2 run right after the observed method is completed. They must have the same name as the observed method, but with the prefix “after.” These methods are responsible for editing the observed method’s results and can access input parameters. They are typically used to change arguments or behavior after the original method call. In summary, Magento 2 after methods helps modify the output and ensure the observed method’s results are edited correctly, with a return value.

Step:02 Create PluginClass for AfterListener at app\code\Bluethinkinc\CustomModule\Plugin\BluethinkCartPlugin

The method afterGetName is the actual plugin method. It is executed after the original getName method. The parameters are:

$subject: An instance of the original class (Product in this case).

$result: The result returned by the original getName method.

In Short, this plugin is designed to intercept calls to the getName method of the Product class and append a custom text to the original product name after the original method is executed.

Around Listener

Around listeners, Magento 2, serve the purpose of altering both the arguments passed to an original method and the values it returns. They allow code to execute both before and after the observed method, effectively overriding it. The method name begins with the “around” prefix, indicating its role.

They are used when you need to modify both arguments and returned values or add behavior before and after the observed method’s invocation. To implement an around listener, the method name should start with “around” and it must return a value.

Step :02 Create PluginClass for AroundListener at app\code\Bluethinkinc\CustomModule\Plugin\class CustomCartPlugin

The method is named aroundAddProduct, indicating that it is an around plugin for the addProduct method of the Cart class. The parameters are:

$subject: An instance of the original class (Cart in this case).

\Closure $proceed: A closure that represents the next method in the chain, i.e., the original addProduct method.

$productInfo: Input parameters to the original addProduct method.

$requestInfo: An optional parameter for additional information.

In short, this plugin is designed to modify the quantity parameter, call the original addProduct method, and then, if successful, send an email with a success message that your quantity has been updated in your cart. Aditionally you need to create a email_templates.xml under etc directory and your custom_email_template file under view/frontend/email directory.

Limitations of Plugins in Magento 2

  • __construct and __destruct:Plugins can’t modify object construction or destruction.
  • Any class that contains at least one final public method:Classes with final public methods can’t be extended.
  • Class methods (like static methods):Static methods are off-limits for plugins.
  • Final classes:You can’t create plugins for classes declared as final.
  • Final methods:Plugins can’t intercept final methods.
  • Non-public methods:Plugins can only intercept public methods.
  • Objects instantiated before Magento\Framework\Interception is bootstrapped:Plugins must work within the Magento 2 interception framework.
  • Virtual types:Virtual types are not directly accessible for plugin implementation.
Amit Soam

Amit Soam

2024-01-19

0

Leave a Reply

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

Find More Blogs

How to Add a Custom Tab to the Customer Order Detail Page in Magento 2

Spread the love Adding a custom tab to the Order Detail

Exception Handling in Java

Spread the love Introduction – Exception:An unwanted

How to add custom less file in Magento2

Spread the love Source files *.css included into layout

Spring Boot Microservices

Spread the love Microservices architecture has become

Implementation of WireMock for better testing

Spread the love WireMock is a flexible and powerful tool

Magento 2: How to selected default option in configurable options?

Spread the love Configurable products in Magento 2 allow

How To Implement Simple JWT Authentication in Django Rest Framework

Spread the love We’ll learn how to use simple JWT

Optimizing Search: Integrating Elasticsearch in Django Applications

Spread the love What is Elasticsearch? Elasticsearch is a

How to create Customer Segments

Spread the love In Magento 2, “customer

Proxy Design Pattern and Requisition List in Magento 2

Spread the love Requisition List in Magento 2 Requisition

bluethinkinc Blogs