Loading...

How to Apply Plugin in Magento 2?

Jayram Prajapati  ·   29 Feb 2024
How to apply plugin in Magento 2
service-banner

Magento 2 has significantly changed e-commerce because of its user-friendly interface and advanced feature technology. Small businesses and store owners do not need more coding knowledge to handle their stores because of Magento 2 technology.

Nowadays, it is easy to code for non-technical persons because of the internet and trustful knowledge resources. In this Elighwalk Magento 2 guide, we discuss about Magento 2 plugin or Magento 2 interceptor. The design pattern 'Interception' is used in plugins. Interception is the dynamic insertion of code that does not affect the original class's functionality.

What is Plugin in Magento?

As discussed above, the plugin injects small code to change the store function. It works without the trouble of any core code for an online store. It quickly sets up in your store and upgrades your function smoothly. Using a plugin, you can modify the class function and call it on some special event in the store process.

Plugins are only used for "public methods.” By calling a function and writing code before, after, or around it, the process helps you modify or optimize the behaviour of original public methods for any class or interface. We can use the plugin's sort order value to avoid problems between plugins. The plugin can be called sequentially to avoid interfering with other plugin classes.

Magento 2 Plugin Types

There are three plugins in Magento 2: Before Plugin, After Plugin and Around Plugin, which you can apply to your store.

  1. Before Plugin (Interceptor):

    Before plugin in Magento 2 is executed before executing the original method. They can modify the arguments passed to the original method or even short-circuit its execution by returning a result without calling the original method.

  2. After Plugin (Interceptor):

    After plugin in Magento 2 is executed after the execution of the original method. They can be used to modify the result returned by the original method or perform additional actions based on its outcome.

  3. Around Plugin (Interceptor):

    The around plugin in Magento 2 is the most robust plugin, as it can fully replace the original method. They are executed before and after the original method, allowing complete control over its behaviour.

Plugins are commonly used for cross-cutting tasks such as logging, caching, and changing input/output data. They are declared in a di.xml file, where you specify the plugin class, the intercept method, and the interception type (before, after, or around).

How to use the Magento 2 plugin Example

Now, we will teach you how you can easily apply the plugin in your store. We can apply three types of plugins before the plugging call, before executing the task, after the plugin call, after the end task and around the plugging call in starting of the process and last end of the process. So start one by one understanding the use of plugins with examples so you can easily create from them.

Before Plugin Magento 2 Example

If you want to change the behaviour of a method before it is executed, you can use method before plugin hooks to inject custom code. This helps you change the method's parameters or return value without modifying the original code.

For Example, Suppose you have a class method that calculates a product's pricing before it is presented. You wish to add a 10% discount to the price before it is displayed. You can do it by applying the before plugin method.

Example
<?php
namespace Vendor\Module\Plugin;

class BeforePricePlugin
{
    public function beforeGetPrice(\Vendor\Module\Block\Product $subject)
    {
        // Modify price before it's retrieved
        $price = $subject->getPrice();
        $discountedPrice = $price * 0.9; // Apply 10% discount
        $subject->setPrice($discountedPrice);
    }
}

After Plugin Magento 2 Example

If you want to change the behaviour of a method after it has been executed, you can use the method after plugin and add customer code. This allows you to modify the method's parameters or outcome value without changing the original code.

For example, you want to send every customer a thank you email after purchase a product from your store. It became easy and automated with the method after the plugin, as you can simply add the code to send the email within the plugin without modifying the original method.

Example
<?php
namespace Vendor\Module\Plugin;

class AfterOrderPlugin
{
    public function afterPlaceOrder(\Vendor\Module\Model\Order $subject, $result)
    {
        // Send thank you email to the customer
        $customerEmail = $subject->getCustomerEmail();
        $emailSender->sendThankYouEmail($customerEmail);
        return $result;
    }
}

Around Plugin Magento 2 Example

If you want complete control over the method's execution, both before and after, the Around Plugin Method helps you create a function that is called before and after the process.

If you want to record how long a method takes to execute, this simple plugging code records every second of the process. Here is simple code about tracking processes using the plugin method.

Example
<?php
namespace Vendor\Module\Plugin;

class AroundMethodExecutionPlugin
{
    public function aroundSomeMethod(\Vendor\Module\Model\SomeClass $subject, callable $proceed, $arg1, $arg2)
    {
        // Before method execution
        $startTime = microtime(true);

        // Execute the original method
        $result = $proceed($arg1, $arg2);

        // After method execution
        $executionTime = microtime(true) - $startTime;
        $this->logger->info("Method execution time: " . $executionTime . " seconds");

        return $result;
    }
}

According to the surveys Magento inform to avoid using of Around Pluging if it not necessary. It can prevent the original function or other plugins in the queue from being executed, increasing stack traces and affecting performance.

Essence

If you want to use the plugin in your Magento 2 store, do proper research, understand how it works with your store, and combine it with your core code. You can contact us for guidance related any Magento 2 store-related queries. Our developers guide you with the right technology to improve the performance of your Magento store with upgrades.

If you want to upgrade your Magento 2 store functionality, here we have: Top 5 Best Magento 2 Extensions to Upgrade Your Store

Our extension is smooth and hassle-free to install in your store. We create a secure and certified Extention for e-commerce stores. It improves your store performance and gives your user the best experience.

FAQs about Magento 2 Plugin

What is a plugin in Magento 2?

How do I apply a plugin in Magento 2?

Do I need to be a developer to apply plugins in Magento 2?

Can I remove Magento 2 plugin?

How to override the plugin in Magento 2?

Jayram Prajapati
Full Stack Developer

Jayram Prajapati brings expertise and innovation to every project he takes on. His collaborative communication style, coupled with a receptiveness to new ideas, consistently leads to successful project outcomes.

Most Visited Blog

Unlock The Power Of Plugins In Magento 2: A Comprehensive Guide

Get started on utilizing Magento 2 plugins with our comprehensive tutorial. Master the art of plugin building and integration to improve the functionality and customization of your e-commerce shop.

How to create a module in Magento 2: Sample Module A Step-by-Step Guide

Embark on Magento 2 journey with confidence! Our step-by-step tutorial module development. Learn how to create a Module to harness the potential of Magento 2 customization for personalized and efficient e-commerce experience.

Duplicate entry error When getting an order using REST API in Magento

When retrieving orders using the Magento REST API, troubleshoot the 'Duplicate Entry' problem. Our guide gives insights and solutions to ensure a seamless and error-free order retrieval experience on Magento platform.