Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 42 ยท Plugins and Events

Plugins (Interceptors)

Learn Magento 2 plugins: before, around and after methods, di.xml declaration, sortOrder, what cannot be plugged, plus a runnable interceptor chain.

A plugin changes what a public method does without editing the class or replacing it. You write a small class with methods named before..., around... or after... plus the name of the method you want to affect, declare it in di.xml, and Magento runs your code at the right moment. Because many modules can plug into the same method, plugins are the main extension tool for Magento, and the reason most customisations survive upgrades.

You already know the ingredients: the Object Manager builds classes from constructors, di.xml configures how, and a generated Interceptor subclass carries the plugins (see Factories, Proxies and Generated Code). This lesson shows how to write the plugin class, declare it, and understand the order things run in. Real Magento code is read-only; the runnable example is a small plain-PHP interceptor chain that imitates the idea.

The three kinds of plugin method

Take any public method on the class you want to affect, say Acme\Greeting\Model\Greeter::greet(string $name): string. A plugin class can define any of these (all optional), named by prefixing the method name with its capitalised form:

  • before (beforeGreet) runs before the original. It receives the subject and the original arguments, and can change the arguments by returning an array of the new ones. Returning null keeps them.
  • around (aroundGreet) wraps the call. It receives the subject, a callable $proceed that runs the next plugin or the original, and the arguments. It decides whether to call $proceed at all, with which arguments, and what to return.
  • after (afterGreet) runs after the original. It receives the subject and the result and must return the (possibly modified) result.

A real plugin class looks like this (read-only):

PHP
<?php
declare(strict_types=1);

namespace Acme\Greeting\Plugin;

use Acme\Greeting\Model\Greeter;

class GreeterPlugin
{
    /** Normalize the argument before the real method sees it. */
    public function beforeGreet(Greeter $subject, string $name): array
    {
        return [trim($name)];
    }

    /** Change the result. */
    public function afterGreet(Greeter $subject, string $result, string $name): string
    {
        return $result . ' Welcome back!';
    }

    /** Wrap the call; only use this when you truly need to. */
    public function aroundGreet(Greeter $subject, callable $proceed, string $name): string
    {
        $result = $proceed($name);
        return strtoupper($result);
    }
}

The after method can also declare the original arguments after the result, which is useful when the result depends on the input. Keep signatures matching the original method so static analysis and your IDE stay happy.

Declaring the plugin in di.xml

The plugin is attached to a type (a class or an interface):

XML
<type name="Acme\Greeting\Model\Greeter">
    <plugin name="acme_greeting_clean_name"
            type="Acme\Greeting\Plugin\GreeterPlugin"
            sortOrder="10"
            disabled="false"/>
</type>
  • name is a unique identifier. Another module can disable your plugin by redeclaring it with disabled="true", or replace the class by reusing the name; pick a name that includes your vendor and module.
  • type is the plugin class (it is built by the Object Manager, so it can use constructor injection).
  • sortOrder controls the order when several plugins target the same method (below).
  • The declaration can sit in the global etc/di.xml or in an area file such as etc/frontend/di.xml or etc/adminhtml/di.xml, so the plugin only runs in that area.

If you plug an interface, the plugin applies to every class implementing it. A plugin on a parent class also applies to subclasses that inherit the plugged method.

flowchart TD
    A["Caller calls greet"] --> B["Interceptor for Greeter"]
    B --> C["before plugins (can change arguments)"]
    C --> D["around plugin (wraps the rest)"]
    D --> E["original greet"]
    E --> F["around plugin finishes"]
    F --> G["after plugins (can change result)"]
    G --> H["Caller receives result"]

The interceptor runs plugin methods around the original method; the exact interleaving of several plugins is described below.

Sort order and several plugins

When two modules plug the same method, sortOrder decides who goes first; a lower number runs earlier. If two plugins have the same sort order, the result depends on module load order, which is a fragile thing to rely on, so give your plugin a deliberate value when order matters. Roughly, in the common case:

  • before methods run from the lowest sortOrder to the highest;
  • an around plugin wraps everything that comes after it (higher sortOrder), so the lowest-sorted around plugin is the outermost layer;
  • after methods wrap the result on the way out.

Real Magento builds its lists in a specific way, and the interleaving between plugins that have around methods and plugins that only have before or after methods has subtle points. If your design depends on the exact order, add a log line in each plugin and confirm it in your Magento version rather than trusting a diagram. The next lesson returns to this.

What you cannot plug

Plugins work through the generated Interceptor subclass, so the subject must be something a subclass could override. These cannot be intercepted:

  • final classes and final methods;
  • static methods;
  • private and protected methods (only public methods work);
  • the constructor;
  • objects created with new or outside the Object Manager, because they are not interceptors;
  • a few very early classes that exist before the plugin system is ready (for example some bootstrap and framework-internal classes).

If the method you need is protected or private, look for a public method in the call chain that you can plug, use an event (Events and Observers), or use a preference as a last resort.

A stand-in interceptor

The stand-in wraps a subject object in a class that builds a chain of plugin steps from a list of plugin definitions. It uses a layered model for clarity, a simplification of what Magento does.

PHP Before, around and after on one method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The plugin with sortOrder 10 ran first, trimmed the name before the audit plugin saw it, and the audit plugin's around wrapped the original call. The caller used greet() as usual and had no idea plugins were involved, which is the point.

Skipping the original

Because an around plugin chooses whether to call $proceed, it can replace the method completely. The example below shows both choices on a stand-in for a price calculation. This is powerful and risky: it hides the original from every other plugin below it, which is one reason around plugins have their own pitfalls lesson.

PHP An around plugin that may skip the original

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you name the plugin method that runs before Greeter::greet()?

    Plugin methods are the prefix before, around or after followed by the original method name with its first letter capitalised.
  2. 2. An after plugin method must do what?

    The after method receives the result and returns the value the caller will see.
  3. 3. Which of these can be intercepted by a plugin?

    Plugins need an overridable public instance method on an object built through the Object Manager. Final, static, private, protected methods and constructors cannot be plugged.
  4. 4. What does disabled="true" on a <plugin> node in another module do?

    Redeclaring a plugin by its name with disabled true switches it off, which is why unique names matter.

Summary

  • A plugin is a class with before, around or after methods named after the original public method, declared in di.xml.
  • Before can change arguments, after can change the result, around wraps the call and decides whether $proceed runs.
  • sortOrder orders plugins; give it a deliberate value when order matters and verify the order in your version.
  • Final classes and methods, static methods, non-public methods, constructors and objects not built by the Object Manager cannot be plugged.
  • Plugins on an interface apply to every implementation.
  • The stand-in imitates the chain with a simplified layered model; the real Interceptor is generated code with extra rules.

Next: Plugin Best Practices and Pitfalls