Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 42 ยท Plugins and Events

Plugin Best Practices and Pitfalls

Avoid classic Magento 2 plugin mistakes: around plugins that skip others, unclear order, plugins versus preferences, performance cost and debugging, with demos.

Plugins are easy to write and easy to get wrong. A plugin that works alone in a small test store can quietly break another module in production, slow down a hot method, or make an upgrade painful. Experienced Magento developers follow a short list of habits that prevent most of these problems, and this lesson explains the reasons behind each one rather than just stating rules.

You will see why an around plugin is the riskiest kind, what actually happens when several plugins share a method, when a preference or an event is a better tool, what plugins cost at runtime, and how to find out which plugins are active. As before, real Magento code and XML are read-only, and the runnable code is a plain-PHP stand-in for the ideas, using a simplified layered model.

Prefer before and after; use around rarely

The three kinds of plugin methods do not carry the same risk:

  • A before plugin changes the arguments. It cannot stop the original from running.
  • An after plugin changes the result. It always runs once the original finishes (or when plugins below it decided to return).
  • An around plugin controls the whole call. It may never call $proceed, it may call it twice, it may change the arguments and the result, and it forces every deeper plugin and the original to be nested inside its stack frame.

So the first rule is: if a before or an after method does the job, use that. Use around only when you really need one of its special powers:

  1. skip the original (a cache hit, a permission check that must stop the flow);
  2. wrap the call with something that must open and close around it (a try/finally, a transaction, a timer);
  3. change the arguments and the result in a way that depends on each other.

If you do write an around plugin, always call $proceed with the (possibly modified) arguments unless skipping is intentional and documented, and always return the value, because forgetting to return silently turns the result into null.

What an around plugin that does not proceed does

When an around plugin returns without calling $proceed, everything that sits deeper in the chain never runs: the plugins with a higher sort order and the original method. Other modules that expected to modify the result never get the chance. The stand-in below uses a layered model to show this on a three-plugin chain.

PHP Order of plugins, and a plugin that does not proceed

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.

For HIDDEN, the tax plugin (sortOrder 30) never ran: the blocker decided the answer first. Whether that is desired depends on the design, but a different module's behavior vanished without an error, which is exactly the problem. In real Magento the same effect applies to every plugin and the original method that sit below an around plugin.

If you must short-circuit, give the plugin a low sort order only when you really want to beat the others, document it, and keep the skipped cases rare and narrow.

Execution order: do not depend on it

Several plugins on one method make a pipeline whose order you only partly control with sortOrder. Two practical consequences:

  • Design plugins to be order-independent. Each should do one small, self-contained thing, such as "add a suffix" or "reject empty names", not "run after the tax plugin has changed the value".
  • Give an explicit sortOrder when order matters, and leave a comment in di.xml saying why. Equal sort orders fall back to module load order, which can change when a module is added or its sequence changes.

If two modules plug the same method and their results interact, test both enabled together, both orders if you can. The previous lesson explains why the exact interleaving of before, around and after methods across plugins has subtle details; confirm it in your Magento version instead of assuming it.

Plugins versus preferences versus events

Pick the lightest tool that works:

Need Tool
Change arguments or the result of a public method Plugin (before or after)
Run extra code when something happens, without needing to change a value Event and observer
Replace an interface's implementation Preference
Replace a whole core class (only one module can win) Preference, as a last resort
Change a protected or private method A public method nearby, an event, or a preference

A preference gives you total control but only one module can use it for a given class. A plugin cooperates with others but can only touch public methods. When a plugin is enough, a preference is the wrong choice.

Performance

A plugin costs a little on every call to the plugged method: the interceptor looks up the plugin list, builds closures for around plugins and calls your method. For a method called once per request that is nothing. For a method called thousands of times per page (price calculation, attribute access, getData-style methods on models inside a loop) it adds up, and several plugins multiply the effect.

Habits that keep this under control:

  • Do not plug a hot method just because it is convenient. Look for a method called once, higher in the flow.
  • Keep plugin bodies cheap: no database queries, no ObjectManager lookups and no file reads inside a plugin on a hot method. Load heavy data once in the constructor or a cached service.
  • Avoid unnecessary around plugins on hot methods; they add an extra closure and a deeper stack.
  • Remember the shared nature of plugin classes: they are built once per type, so do not keep per-call state in properties.

The second stand-in counts how many times plugin code runs, so the multiplication is visible without relying on timing.

PHP Counting plugin calls on a hot 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.

Three small plugins turned 2,000 reads into 6,000 extra method calls. Each call is cheap, but the point is that cost scales with how often the method runs.

Debugging plugins

When a value comes out wrong, find out who touched it:

  • Run bin/magento dev:di:info "Vendor\Module\Class" (available in 2.4 releases; check bin/magento list if your version differs). It prints the preference and plugins affecting a class, so you can see unexpected plugins from other modules.
  • Open the generated interceptor in generated/code/.../Interceptor.php. It shows exactly which methods are intercepted.
  • Search di.xml across vendor/ and app/code/ for the class name and the method name.
  • Put a breakpoint in the plugin (Xdebug) and read the call stack; interceptor frames and $proceed closures show the nesting.
  • Temporarily disable a suspect plugin with disabled="true" in a test module to confirm it is the cause.
  • After changing plugin declarations, flush the cache and, in production mode, recompile so the interceptor is regenerated (see Factories, Proxies and Generated Code).

Other common mistakes

  • Forgetting to return the result in an after or around method.
  • Wrong signature: the subject comes first, then the arguments; for after, the result comes second.
  • Plugin on a final or private method that silently never fires (see the limits in the previous lesson).
  • Using the Object Manager inside a plugin instead of constructor injection.
  • Changing return types: returning a different type than the original method promised breaks callers.
  • Calling the subject's method again from the plugin on the same method, which can loop.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you prefer before or after plugins over around plugins?

    Around controls the whole call, so a mistake can hide the original and other modules' behavior. Before and after are narrower and safer.
  2. 2. An around plugin returns a value without calling $proceed. What happens to plugins with a higher sortOrder on that method?

    Everything deeper than an around plugin is only reached through $proceed, so not calling it skips them.
  3. 3. You want to run extra code when an order is placed and you do not need to change any value. Which tool is the best fit?

    Events are meant for reacting to something that happened, with less coupling than a plugin or preference.
  4. 4. Why can a cheap plugin still hurt performance?

    The overhead is paid per call, so plugging methods that run thousands of times per request adds up.

Summary

  • Choose before or after first; use around only to skip, wrap with try/finally, or change arguments and results together.
  • An around plugin that does not call $proceed hides deeper plugins and the original.
  • Make plugins order-independent, and set an explicit sortOrder with a comment when order matters.
  • Use events for reactions, plugins for public-method changes, preferences for implementation swaps.
  • Plugin cost is per call: avoid plugging hot methods and keep plugin bodies light.
  • Debug with dev:di:info, the generated interceptor, Xdebug and disabled="true".

Next: Events and Observers