in

How to Create a Magento 2 Plugin Interceptor: A Simple, Practical Guide

Learn Magento 2 plugin interceptor creation with a simple, practical walkthrough. You’ll see how interceptors change method calls, choose the right plugin type, prepare your module, and register the target class, method, and sort order. Then write and test your plugin, clear caches, and troubleshoot common issues with confidence.

Need to customize Magento 2 behavior without changing a core class? A plugin, also called an interceptor, lets you run code before, after, or around a public method while keeping your changes separate from the original code. It’s a flexible way to extend a store and make future maintenance easier.

This practical guide walks you through Magento 2 plugin interceptor creation, from defining the plugin in your module’s di.xml file to writing and testing its methods. Follow along to build a simple example and understand the key details that help your plugin work as expected.

Understand Magento 2 plugin interceptors and when to use them

Before adding a plugin to your module, it helps to picture what happens when Magento calls the method you want to customize. That call path determines which plugin type fits—and whether a plugin is the right tool at all.

First, let’s follow a method call through Magento’s interception system. Seeing where your code runs makes the differences between the available plugin types much easier to judge.

How an interceptor changes a method call

When Magento resolves an eligible class through its dependency injection system, it can provide an interceptor instead of the original class instance. The interceptor checks for configured plugins around a public method call, runs their applicable logic, and then invokes the original method as part of that sequence.

For example, if a checkout service calculates a total, a plugin could adjust data before the calculation or log the result afterward. Plugin order can matter when several modules target the same method: Magento uses each plugin’s sortOrder to organize execution. Keep in mind that plugins do not intercept every method; constructors, static methods, and final or non-public methods are not valid targets.

This call sequence also explains why a plugin should stay focused. It is usually a good fit for a small change to an existing public method, while a larger redesign may be clearer in a dedicated service or a class preference.

Once you know where the plugin can run, choose its type based on the moment your customization needs to act. The three options offer different levels of control, so the simplest one that meets the requirement is generally the safest choice.

Choose the right plugin type for your customization

Each plugin method follows a naming pattern that combines the target method with its type. For a target method named execute, the corresponding plugin methods are beforeExecute, afterExecute, and aroundExecute.

  • Before plugins run before the original method and can modify its arguments. Use one when you need to adjust input, such as normalizing a value.
  • After plugins run after the original method and can inspect or change its result. They work well for enriching returned data.
  • Around plugins wrap the original call and receive a $proceed callback. They can change arguments or results, but can also prevent the original method from running.

Prefer before or after methods when they are enough; they are easier to reason about and less likely to disrupt other extensions. Choose an around plugin only when you genuinely need to control whether or how the original method executes, and make sure to call $proceed unless skipping that method is intentional.

Prepare your module for Magento 2 plugin interceptor creation

With the plugin type decided, the next step is to give Magento a module it can discover and a configuration that points to the right class. A tidy setup makes Magento 2 plugin interceptor creation easier to test and troubleshoot.

Start by laying out the module and checking whether it needs to load after another module. Then you can register the plugin and specify its target.

Create the module files and declare the dependency

A Magento module needs a registration file and a module declaration before its dependency injection configuration can be loaded. Create these under app/code/Vendor/InterceptorDemo, replacing Vendor and InterceptorDemo with your namespace and module name.

The basic files are registration.php and etc/module.xml. The registration file registers the module with Magento; in module.xml, declare the module name and, when needed, its load order. For example, if your customization targets a class from MagentoCatalog, add it to the sequence:

<module name="VendorInterceptorDemo" setupversion="1.0.0">
    <sequence>
        <module name="MagentoCatalog"/>
    </sequence>
</module>

Sequence controls module load order; it is not a substitute for declaring a required Composer package in composer.json. Once the module is in place, add the plugin configuration in its etc/di.xml file.

Register the plugin in di.xml

The dependency injection configuration connects a plugin class to the class it will extend. Use the global etc/di.xml when the plugin should apply throughout the application; choose an area-specific file, such as etc/frontend/di.xml, when it should apply only in that area.

Add a type node for the target class and a plugin node with a unique name and the plugin class’s fully qualified name:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="VendorModuleModelTargetClass">
        <plugin name="vendorinterceptordemotarget"
                type="VendorInterceptorDemoPluginTargetPlugin"
                sortOrder="10"/>
    </type>
</config>

Configure the target class, method, and sort order

Before writing the plugin methods, confirm that the configured target is the class Magento actually resolves and that the method is eligible for interception. The class name goes in the XML; the method is identified by the plugin method’s name, such as beforeExecute for a target method named execute.

Give each plugin a unique name to avoid collisions with other modules. Set sortOrder when ordering matters: lower values run earlier for before and around plugins, while after-plugin execution follows the reverse order. With the target and ordering settled, you’re ready to implement the plugin class.

Complete Magento 2 plugin interceptor creation and verify the result

The configuration now points Magento to your plugin class. Next, add the method that makes the change, refresh generated configuration, and confirm that the target method behaves as expected.

Start with the smallest implementation that meets your requirement. The example below uses a before plugin; adapt the method name and arguments to match your target class.

Write the plugin class and implement a before, after, or around method

Create Plugin/TargetPlugin.php in your module. For a target method called execute, Magento recognizes the plugin method by its before, after, or around prefix.

Here’s a before-plugin example that normalizes a string argument. Replace the argument and return types with those required by the actual target method.

<?php
namespace VendorInterceptorDemoPlugin;
class TargetPlugin
{
    public function beforeExecute(
        VendorModuleModelTargetClass $subject,
        string $value
    ): array {
        return [trim($value)];
    }
}

A before method returns an array of replacement arguments in the target method’s parameter order. An after method instead receives the original result and can return an adjusted result; an around method receives a $proceed callback and must call it when the original method should run. Keep the subject parameter first, and match the target method’s signature closely.

Once the class is saved, Magento needs to rebuild its generated dependency-injection data before you can reliably test the change.

Clear generated files and cache

In a development environment, run these commands from the Magento root after adding or changing plugin configuration. They remove generated code and clear cached configuration so Magento can discover the updated setup.

rm -rf generated/code/ generated/metadata/
bin/magento cache:clean

If the module is new, run bin/magento setup:upgrade as well. In production mode, regenerate compiled dependency-injection code with bin/magento setup:di:compile and deploy static content when your changes require it.

With refreshed configuration in place, test through the application path that calls the target method—not just by instantiating the plugin class directly.

Test the plugin and troubleshoot common issues

Trigger the relevant storefront or admin action, then check the result and var/log/ for errors. If the plugin does not run, verify the following before changing the implementation:

  • Target and area: Confirm the XML class name is correct and the configuration file applies to the area being tested.
  • Method eligibility: Ensure the target method is public and not static or final.
  • Registration: Check the plugin class namespace, unique plugin name, and module status.
  • Arguments and return values: Match the target signature; a before plugin must return arguments in the correct order.

When errors persist, inspect the merged dependency-injection configuration and logs, then clear the relevant cache again. This final check completes Magento 2 plugin interceptor creation and helps confirm the customization works without altering the original class.

Extend Magento 2 behavior with confidence

Magento 2 plugin interceptors offer a maintainable way to customize public methods without changing core code. The key is to choose the least complex plugin type that fits your goal, configure the target and execution order carefully, and keep your plugin focused.

Successful Magento 2 plugin interceptor creation also depends on testing the change through the application flow that uses it. Check the configuration, method signature, and logs if the plugin doesn’t behave as expected. With these practices in place, you can extend your store more confidently while keeping future updates easier to manage.

Leave a Reply

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

      Written by Maeve Rodriguez

      Maeve is a Business Content Writer and Front-End Developer. She's a versatile professional with a talent for captivating writing and eye-catching design.