How to Create and Use Plugins in Magento 2

How to Create and Use Plugins in Magento 2

When starting with the Magento 2 store, you might have many questions.

You may have encountered terms like extensions and modules, but also “Magento 2 plugins.” While plugins aren’t new, they can sometimes be confusing.

Just to introduce, the Magento 2 plugin, or interceptors, is a class that changes the behaviour of public class functions by intercepting function calls and executing code before, after, or around them.

Based on their usability, plugins are pretty similar to extensions or modules because both are added to the default Magento and are often developed by a third party.

In this guide, we’ll explain everything you need to know about Magento 2 plugins and Magento plugin development. Stay tuned!

Advantages of Using Magento 2 Plugins

Magento 2 plugins are often confused with extensions, but they serve distinct purposes.

To fully grasp the significance of Magento 2 plugins, it’s essential to understand their benefits and how they enhance development capabilities.

For module developers, Magento 2 interception plugins provide the ability to:

  • The redirect method calls on object manager-controlled objects and executes programmatic actions.
  • Modify the return value of method calls to achieve custom outcomes.
  • Alter the arguments of method calls before they are processed.
  • Ensure smooth execution even when multiple modules interact with the same method.

If you’re new to this approach, adapting to its performance characteristics may take some time. However, once you master it, you’ll be able to efficiently update and optimize your store, such as dynamically modifying product prices using plugins.

If you need further insights beyond this guide, feel free to reach out to the Mage E-commerce developer team for expert guidance on creating and using Plugins in Magento 2.

The Magento 2 Plugins can’t be used with:

  • Non-public methods
  • Static methods
  • 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
  • __construct

Suggested Reading: Understanding Magento 2’s Architecture: A Simple Yet Complete Guide

Types of Interceptors (Plugins) in Magento 2

Magento 2 offers three types of interceptors or you can say 3 types for Magento plugin development: Before Plugin, After Plugin, and Around Plugin.

Each serves a distinct purpose and operates at different points in the execution flow of an observed method.

1. Before Plugin (Before Listener)

Before listeners execute before the original method is executed.

They are mainly used to modify method arguments or introduce additional behaviour before execution.

  • Execution Order: Runs first, before the observed method.
  • Functionality: Allows modification of method parameters before execution.
  • Syntax: beforeMethodName()
  • Example Usage: Changing method arguments before they reach the original function.

2. After Plugin (After Listener)

After methods execute after the observed method is finished, these methods must have the same name as the observed one’s name while the prefix label is “after”. These are useful when modifying the output of a method or adding post-processing logic.

  • Execution Order: Runs after the observed method has finished.
  • Functionality: Allows modification of the return value of the original method.
  • Syntax: afterMethodName()
  • Example Usage: Adjusting the result returned by a method before it reaches the caller.

3. Around Plugin (Around Listener)

Around listeners provide the most control, executing both before and after the observed method.

They can override a method entirely, making them powerful but potentially performance-heavy.

  • Execution Order: Runs before and after the observed method.
  • Functionality: Allows modification of both input parameters and return values.
  • Syntax: aroundMethodName()
  • Example Usage: Wrapping additional logic around a method, such as adding logging or conditionally modifying behavior.

Note: Avoid using Around Plugins unless necessary, as they increase stack traces and can impact performance.

Choosing the Right Plugin Type

  • Use Before Plugins when you need to alter method parameters before execution.
  • Use After Plugins when you want to modify the returned result.
  • Use Around Plugins when you need complete control over both input and output.

By leveraging Magento 2 interceptors wisely, Magento 2 plugin development companies and developers can enhance functionality while keeping core files intact, ensuring seamless upgrades and maintainability.

Recommended Read: Essential Steps for Setting Up a Magento 2 Local Development Environment

Creating a Magento 2 Plugin: A Step-by-Step Guide

Magento 2 plugins, also known as interceptors, allow developers to modify the behavior of existing classes without altering their core code.

Below is a structured approach to creating a plugin using an example class.

Step 1: Define the Target Class

Let’s consider a sample class for demonstration:

<?php

namespace MageEcommerce\HelloWorld\Controller\Index;

class Example 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;

}

}

Step 2: Declare the Plugin in di.xml

To create a plugin, you need to register it in your module’s di.xml file:

<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:noNamespaceSchemaLocation=”urn:magento:framework:ObjectManager/etc/config.xsd”>

<type name=”MageEcommerce\Tutorial\Controller\Index\Example”>

<plugin

name=”MageEcommerce_Tutorial_Plugin”

type=”MageEcommerce\Tutorial\Plugin\ExamplePlugin”

sortOrder=”10″

disabled=”false”

/>

</type>

</config>

  • type name – The class being observed.
  • plugin name – A unique identifier for the plugin.
  • plugin type – The plugin’s class name (follows Vendor\Module\Plugin\ClassName naming convention).
  • sortOrder (optional) – Defines execution order when multiple plugins observe the same method.
  • disabled (optional) – Set true to disable the plugin (default: false).

Step 3: Create the Plugin Class

<?php

namespace MageEcommerce\HelloWorld\Plugin;

class ExamplePlugin

{

}

Step 4: Implement Plugin Methods

Magento 2 supports three types of plugin methods: Before, Around, and After.

1. Before Methods

Executed before the observed method, allowing modification of its arguments. If no modification is needed, it returns null.

<?php

namespace MageEcommerce\Tutorial\Plugin;

class ExamplePlugin

{

public function beforeSetTitle(\MageEcommerce\Tutorial\Controller\Index\Example $subject, $title)

{

$title = $title . ‘ to ‘;

echo __METHOD__ . ‘</br>’;

return [$title];

}

}

2. Around Methods

Executed both before and after the observed method.

Use with caution, as it can impact performance.

<?php

namespace MageEcommerce\Tutorial\Plugin;

class ExamplePlugin

{

public function aroundGetTitle(\MageEcommerce\Tutorial\Controller\Index\Example $subject, callable $proceed, …$args)

{

echo __METHOD__ . ‘ – Before proceed() </br>’;

$result = $proceed();

echo __METHOD__ . ‘ – After proceed() </br>’;

return $result;

}

}

  • The $proceed() callable ensures execution of the next method in the chain.
  • If $proceed() is not called, subsequent plugins and the original method won’t execute.

3. After Methods

Executed after the observed method, allowing modification of its return value.

<?php

namespace MageEcommerce\Tutorial\Plugin;

class ExamplePlugin

{

public function afterGetTitle(\MageEcommerce\Tutorial\Controller\Index\Example $subject, $result)

{

echo __METHOD__ . ‘</br>’;

return ‘<h1>’. $result . ‘ MageEcommerce.com’ .'</h1>’;

}

}

  • Modifies the return value of getTitle().

Best Practices

  •  Follow Magento’s naming convention (beforeMethodName, afterMethodName, aroundMethodName).
  • Use before and after plugins instead of around wherever possible (to avoid performance overhead).
    In your documentation, link the observed method’s full path for easy reference in IDEs.
  • By implementing Magento 2 plugin development correctly, you can modify core functionalities without overriding core files, ensuring smooth and upgradable Magento development.

Read More: Maximizing Site Performance: A Guide to Content Delivery Setup for Magento 2

Wrapping Up

We tried our best to explain everything in one blog from the advantages of using plugins, to how to create one, but still, if you have any confusion around how to create a plugin in Magento 2, then please let us know as Mage Ecommerce has the largest Magento plugin development team with expert developers who are available round the clock to assist you.

Author Image

Dhiren is Digital Marketing Manager and also Magento Support and Solutions Provider at Rock Technolabs. He is passionate about anything related to Digital Marketing. He is passionate about using the power of search to help local businesses succeed.

Leave a Reply

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