Magento plugins versus observers versus preferences

Magento offers three extension mechanisms that change behavior in different ways. This page explains when each fits, where plugins stop working, and how sort order settles overlapping changes.

On this page

Magento plugins versus observers versus preferences: which mechanism fits a change

Choose the least invasive mechanism that reaches the code point you need. For a change that must survive 2.4.x patch cycles, that usually means an observer or a plugin, and a preference only when no narrower option exists. A plugin is an interceptor that runs before, after or around a public method on a class. An observer is a listener attached to a named event that Magento dispatches. A preference tells the dependency injection system to use your class in place of a core class, declared in a di.xml file. Each is registered from a module, and modules follow the PSR-4 structure that Adobe's developer documentation describes for Magento Open Source extensions, alongside themes and language packages.

The practical test is the code point. If the change needs to read or adjust arguments or the return value of a public method, a plugin fits. If it needs to react when something happens, such as an order being placed, an observer fits, provided Magento dispatches an event at that point. A preference replaces the whole class, so every other module that depends on that class now depends on your replacement. Ask the developer to name the event, method or class being changed, then confirm in the core source on the magento/magento2 repository that the event is dispatched or the method is public and not final. Plugins cannot intercept every method, so the check is not optional.

Which mechanism fits which kind of change

This table compares the three Magento extension mechanisms across the code points each reaches, timing, interaction with other extensions and upgrade risk. Read each row as a question to ask about your change, then use the last row to decide when to avoid each mechanism. The main takeaway is that plugins suit most behavior changes, observers suit event-driven side effects, and preferences should be a last resort because only one can win.

CriterionPlugins (interceptors)Observers (event handlers)Preferences (class rewrites)
Code points reachedPublic methods of classes and virtual types, including many service contractsOnly code that dispatches a named event, such as product save or checkout successAny class that Magento instantiates through dependency injection, including non-public behavior
Timing relative to the original callBefore, after or around the method, with access to arguments and return valueAfter the event fires, with no control over the code that dispatched itReplaces the whole class, so the original logic runs only if your copy calls it
Interaction with other extensionsSeveral plugins can apply to one method, ordered by sort orderSeveral observers can listen to one event, and their order is not guaranteed unless configuredOnly one preference can win per class, so a second extension rewriting the same class conflicts
Upgrade riskLow to moderate, since the target method signature must stay stableLow, since event names change rarely, but payload contents can change between releasesHigh, because copied logic drifts from upstream changes in later patch releases
Good fitAdding logic around a public method, changing a returned value or validating inputReacting to a save, import or order event where you only need a side effectAlmost never; use only when no plugin point exists and the class is fully owned by you
Avoid whenThe target is final, private, a constructor, or a non-service objectYou must change the data flowing through the call or prevent the original actionAnother extension rewrites the same class, or you only need to change one method
What to confirm in your codeRun the Magento coding standard and check that each intercepted method is public and has a stable signatureConfirm the event name and payload for each target release in your upgrade checklistList every preference in di.xml and confirm none overlaps with a Marketplace extension before build

How plugins intercept public methods and where they stop

A plugin wraps a public method on a class that Magento manages through dependency injection, and it does so in three forms: before methods receive the arguments and can change them, after methods receive and can change the return value, and around methods receive the original call as a callable and decide whether it runs at all. The plugin is declared in di.xml under the target type, with the plugin class, a name and a sortOrder. Because the interception is generated code around the target class, a plugin only sees calls that go through the object Magento instantiates. Code that creates the class directly with new, or that bypasses the DI container, runs without the plugin. Before you choose a plugin for a change, confirm that the call path you need actually goes through a managed instance.

The limits matter as much as the mechanics. Plugins cannot intercept non-public methods, constructors, final classes or final methods, and some static calls fall outside interception. A plugin also cannot target a method that is only reached through an internal property access or a direct function call. These constraints drive design: if the behavior you need sits in a private method, a constructor argument or a final class, a plugin is the wrong tool and you will need an observer, a preference or a change at a different public seam. Treat this list as a starting point, not a complete catalog, and confirm the current rules in the Adobe PHP development documentation for your exact Magento Open Source version, such as Adobe Commerce PHP development overview, before you commit a design.

Plan the verification step into the work, not after it. Ask the team building the change to name the public method being intercepted and to show, with a test or a trace, that the plugin fires on the real request path, including from cron, the API and the admin where relevant. Record the plugin class, its sortOrder and the target method in the design note, since those are the facts a later upgrade or a second extension will need. If a vendor cannot tell you which methods their plugins intercept and why, ask for that list before you accept the extension into your codebase.

Why around plugins and preferences cause conflicts

Around plugins and preferences change what a method or class does at its core, so they can collide with other modules in ways a simple after plugin never would. The five risks below share one root: a second module that assumes the original behavior still holds. Check each one during code review and again after every core patch.

Two modules around the same method

When two modules each declare an around plugin on the same public method, each one decides whether the next callable runs. If one module skips the call, the other module's logic and the original method both stop running. The symptom is a method that returns a value without executing parts of the chain. Check the di.xml of every installed module for around declarations on shared methods, and confirm which module the sort order puts first.

Preference replacing an extended class

A preference tells Magento to construct a different class wherever the original is requested. If another module extends the original class or attaches plugins to it, those changes may no longer apply to the replacement. The symptom is a feature that works in one module but silently stops working after a second module adds a preference. Before adding a preference, search the codebase for classes that extend or plug into the same type.

Preference dropping upstream fixes

A preference copies the body of a core class into a custom class and changes it. When Adobe ships a security or bug fix to the original file, the copy keeps the old code because it never inherits the change. The symptom is a known defect or vulnerability that reappears on a store that was patched on paper. Track every preference in a register, and compare each copied class against the upstream file in every release that Adobe publishes.

Plugin order changing after a module is added

Magento applies plugins in an order set by the sortOrder attribute, and a new module with a lower value can move its plugin in front of existing ones. Behavior that depended on the previous order then changes without any edit to the original modules. The symptom appears only after a deployment that added a module, which makes it hard to trace. Pin sortOrder values in your own modules and review the effective plugin order after every installation.

Change breaking after a core patch

A plugin that depends on a method signature, a return type, or an internal detail of a core class can fail when Adobe changes that code in a patch release. Around plugins are especially exposed, because they must match the original signature exactly. The symptom is an error or a silent change in output after a routine patch, often on the first request that reaches the changed method. Keep a test suite covering each plugin, and run it against each patch release on a staging copy before production.

Upgrade guide

How sort order decides which plugin runs first

This sequence shows how to declare plugin order in di.xml, predict how before, after and around plugins stack, and confirm the resulting order on a staging store before anyone relies on it. It treats sort order as a way to settle ordering between plugins that already agree on design, not as a repair for conflicting changes.

  1. Inventory every plugin on the target method

    Before changing anything, list every plugin registered against the public method you are working on, across all installed modules. Search each module's etc/di.xml files for the target class and method name, and record the plugin name, the plugin class, the type (before, after or around) and any sortOrder value already declared. The developer or lead who owns the change does this work, and the output is a short table that the team can review. The step is done when every registration is accounted for, including ones from third-party extensions that the team did not write.

  2. Declare the plugin with a sortOrder attribute

    Add or adjust the plugin entry in the custom module's etc/di.xml under the target type's plugin section. Set the name, the plugin class and the sortOrder attribute, and use a value that fits the order recorded in the inventory. The file is the only place this is configured, so the change lives in version control with the rest of the module. The step is complete when the XML validates against the Magento configuration schema and the module can still be enabled and compiled without errors in a development environment.

  3. Predict the call order on paper

    Write down the expected sequence before running anything. Lower sortOrder values run first for before plugins, and the same ordering applies to the before phase of around plugins. After plugins run in the reverse direction of their before counterparts, so the lowest value wraps the outermost layer. Around plugins nest: the first around plugin's code surrounds the next, and each around plugin decides whether and when to call the next layer. The output is a numbered list of expected calls that the reviewer can compare with the test results.

  4. Handle ties and undeclared order deliberately

    When two plugins declare the same sortOrder, or when one has no sortOrder at all, the order between them is not something the team should assume. Confirm the behavior against the Magento version in use, since tie handling and default values depend on the framework implementation, and check the Adobe developer documentation for the current guidance. Then assign distinct values to every plugin that must run in a fixed order. The step is done when no two plugins on the same method share a value that matters to the business logic.

  5. Confirm the order with a temporary logging probe

    On a non-production store, add a temporary log line at the start of each plugin's method, writing the plugin name and the phase to a dedicated log file. Clear the compiled code and generated cache, then trigger the target method through the storefront or an admin action. Compare the log sequence with the prediction from the earlier step. Remove the probe before the change moves to the next environment. The step is done when the logged order matches the prediction for each path that calls the method, including the admin, API and cron paths where they apply.

  6. Test the outcome, not only the order

    Order is only useful if the final result is correct. Run the functional checks that depend on the changed method, such as price calculation, cart totals or order placement, and confirm the output matches what the business expects. Use the project's automated tests where they exist, and record any scenario that changes when the order changes. The step is complete when the expected output is documented for each scenario and the team has signed off on it in the change record.

  7. Record the design decision and stop at the ordering fix

    Document why the plugins need this order, which modules are involved and what each plugin assumes about the others. If two plugins are changing the same data in incompatible ways, or if the order keeps shifting with each extension update, treat it as a design conflict and move the work to refactoring, a single owner for the behavior, or removal. Sort order settles which plugin runs first, but it does not decide whether both should exist. The step is done when the change record names the owner of each plugin and states whether the sort order is a stable fix or a temporary measure.

How a call flows through preferences, plugins and observers

The diagram starts with code that asks the dependency injection container for a class. The container first applies any preference that swaps the implementation, then wraps the public method in the plugin chain, where before, around and after methods run in sort order. Separately, the code dispatches an event that observers receive, and observers never see the method call itself. When you review a change, check which class the container actually resolves and what order the plugins run in.

Preferences run first, then plugins wrap the method, while observers receive events separately.

Choosing a mechanism for a specific change

When the change needs to modify the input or output of a public method on a class you do not own, a plugin is usually the first choice. A plugin wraps the call with before, after or around methods, so the original logic stays in place and your code runs alongside it. This keeps your change narrow and survives most core patches because the original class is untouched. Illustrative example: adding a surcharge to the price returned by a pricing method by writing an after plugin that adjusts the return value.

  • Recommended mechanism: a plugin on the public method, using an after method for return value changes and a before method for argument changes.
  • Reason: the original class and its other callers keep working, and the plugin is declared in di.xml so it can be disabled without editing core files.
  • Limit: plugins cannot intercept final methods, private methods, constructors or most non-public code paths.
  • Fallback if not interceptable: a preference for the class if you own the replacement behavior, or an observer if the change only needs to react to a dispatched event.
  • Watch for: around plugins, which replace the original call and can block other plugins on the same method unless they call the proceed closure.

Before committing to a plugin, confirm the target method is public and not final in the Magento version you run.

Setting up a plugin, observer or preference safely

This sequence confirms the target code on the supported 2.4.x release, declares the extension point in a module's configuration, and ends with checks that show the change works and does not collide with other modules. Each step names the output a reviewer can inspect before the change is accepted.

  1. Confirm the target class and method

    The developer opens the target class and method in the exact Magento Open Source 2.4.x release the store runs, not in a copy from memory or an older forum thread. They note the signature, whether the method is public, whether it is final or static, and whether the class is a preference candidate because it is an interface or a service contract. Done means the team has a written reference to the file path, method name and release version, and a reviewer can reproduce the lookup from the codebase on that release.

  2. Choose the mechanism for the change

    The developer decides between a plugin (around, before or after a public method), an observer (a dispatched event), and a preference (a replacement class for an interface or type). Plugins cannot intercept final or private methods or some non-public code paths, so if the target falls outside those limits the team considers an observer or a documented extension point instead. Done means the choice is recorded in the change ticket with the reason, and a reviewer agrees the chosen mechanism is the narrowest one that works.

  3. Declare the extension in the module configuration

    The developer adds the declaration to the module's etc/di.xml for plugins or preferences, or to etc/events.xml for observers, using the module's own namespace and PSR-4 structure. For a plugin, the entry names the target type, the plugin class and the method prefix; for a preference, it names the interface and the replacement type. Done means the declaration exists only in the module's own files, the XML validates, and the plugin or observer class follows the naming and file layout the module already uses.

  4. Set sort order where more than one module applies

    When the target may already be intercepted or observed, the developer sets sortOrder on each plugin or observer so the execution order is deliberate and not left to module load order. Preferences do not stack in the same way, so for preferences the team confirms that only one module declares the replacement for a given interface. Done means every declaration that touches the same target has an explicit order or a documented reason why ordering does not matter, and that record is included in the review.

  5. Compile, deploy and run the functional tests

    The developer runs the Magento compile and deployment commands for the environment, then exercises the changed path through the storefront, admin or API, and runs the module's unit and integration tests. Done means the compile completes without generated-code errors, the changed behavior is visible in the targeted flow, and the tests that cover the original method still pass. The team keeps the compile and test output with the ticket so later upgrades can be compared against it.

  6. Check for overlapping declarations across modules

    The developer searches all installed modules, including vendor packages and any in-house modules, for other di.xml and events.xml entries that target the same class, method or event, and reviews the resolved configuration in the compiled output. Overlaps are either given explicit sort orders, removed, or documented as intentional. Done means a written list of overlapping declarations exists, each with a decision, and a reviewer has confirmed no hidden preference or unordered plugin remains.

  7. Run the Upgrade Compatibility Tool and coding standard checks

    Before merge, the team runs Adobe's Upgrade Compatibility Tool against the target release and runs the Magento coding standard checks on the changed files. These are checkpoints, not proof of safety: the tool flags known incompatibilities, and the coding standard flags structural issues, but neither confirms the business behavior. Done means both reports are attached to the change, every finding is either fixed or accepted with a written reason, and the reviewer records the release version the reports were run against.

  8. Record the extension point for future upgrades

    The developer writes a short record of the target class and method, the mechanism, the sort order, the release the change was verified on, and any overlaps found. The record is stored with the module documentation so the next upgrade review knows what to retest. Done means a maintainer can find the extension point, its purpose and its test coverage without reading the whole module, and the upgrade checklist references the record.

Security and operational considerations for overriding core behavior

Each override you choose, whether a plugin, observer or preference, changes code paths that payment, security and operations teams depend on. The cards below cover the places where an interceptor or rewrite can shift PCI DSS scope, weaken browser or admin controls, hide behavior from logs, or survive a deployment in compiled form. Review them together before any override reaches production.

Payment and checkout code paths

Plugins on payment methods, quote totals, place-order and checkout controllers can change where cardholder data is captured, transmitted or logged. A small change to an after-plugin on the payment method can move a page into a different scope for PCI DSS assessment. Before approving an override here, ask which page renders the card fields, whether any hook touches the data passed to the gateway, and whether your QSA has reviewed the change. Keep payment interceptors in a separately owned module with its own review step.

PHP development docs

Content Security Policy and admin controls

An override can silently remove a directive, add an inline script or reopen a route that the core restricts. Magento supports Content Security Policy headers from 2.3.5, and from 2.4.7 CSP runs in restrict mode by default on storefront and admin payment pages. A plugin that alters header output or injects scripts can break that restriction. Test every change to CSP, admin login, role checks and two-factor settings with the policy in its enforced state, not in report-only mode.

CSP docs

Logging and debugging interceptors

Stacked plugins and observers make a single method call run through several hidden steps, so a wrong value can be hard to trace. Log which interceptor modified an argument or return value, and avoid logging full request payloads, tokens or customer data while doing so. Confirm that debug logging is disabled in production and that log files are not web-accessible. Ask your developers to document how to reproduce a plugin chain in a staging environment.

Cache and compiled DI after deployment

Plugins and preferences are read from generated code and configuration caches, so a deployment can run old interceptors until the caches and generated classes are rebuilt. Stale generated code can also cause a preference to appear to be ignored. Include the compile, static content deploy and cache flush steps in the release runbook, and verify the changed behavior on the production build before closing the change. Confirm the exact commands your deployment pipeline uses with your Magento administrator.

Reviewing third-party extension code

Extensions from vendors or agencies can contain plugins that alter core behavior in ways the Marketplace listing does not describe. Review each interceptor for what it reads, writes and calls, especially outbound HTTP requests and changes to authentication or payment flows. Check that the code matches the version you purchased, that obfuscated or encoded files are absent, and that the vendor can explain each override. Treat this review as a gate before installation, not after an incident.

Record of overrides for incident response

During an incident, responders need to know which plugins, observers and preferences change a given class, and when each was added. Keep a register that lists the module, the target class or method, the mechanism, the sort order, the owner and the approval reference. Update it in the same change that adds the override, and review it at each upgrade. Ask your team to confirm that the register can be produced in under a working day, because it is the first artifact an investigator will ask for.

Questions buyers ask before choosing an extension mechanism

Is a preference ever the right choice in Magento Open Source?

Yes, but only when you intend to replace a class completely and no other module needs to change its behavior. A preference tells Magento to load your class instead of the original for a given type, so every other module that also declares a preference for that type conflicts with yours and only one can win. Plugins and observers let several modules coexist around the same code. Teams usually reserve preferences for narrow cases such as a deliberate replacement of a single service, and they document the reason in the module so the next engineer can see why the original class is no longer in use. Ask the developer to list every preference in the codebase and confirm which ones an installed extension also declares.

How much more effort does a plugin change take than an observer?

The difference depends on the change more than on the mechanism. A plugin wraps a public method and can run code before, after or around it, so the developer must understand the method signature, return values and any other plugins on the same method. An observer reacts to a named event that Magento dispatches, which makes it simpler to add behavior at a known point but gives no control over the result of the operation. Plugins generally need more analysis up front and more tests, while observers need careful checks that the event carries the data the handler needs. Ask for the analysis of each target method and the list of events considered before any code is written.

What does the work need from our in-house team?

The in-house team needs to provide access to the codebase and a staging environment that matches production closely enough to reproduce behavior. Someone who knows the business rules must confirm which outcomes are correct, because the mechanism choice often depends on rules that exist only in the team's heads. The team also needs to review the design, especially which classes are touched and why, and to own the module after delivery. Ask the provider to state these inputs in the written scope so that staffing gaps show up before the build starts rather than during testing.

Can our own developers make these changes without a partner?

Yes, if they have working knowledge of Magento's dependency injection configuration, the event system and the module structure defined in di.xml and events.xml. Developers who have not worked with plugin ordering or preferences often introduce conflicts that appear only when a second extension is installed or upgraded. A useful test is whether the team can explain the execution path for the method they are changing and can name the other modules that touch it. Where that knowledge is thin, a short review by an experienced developer is usually cheaper than a failed upgrade. Ask whether the in-house team would own the resulting code after handover.

How do upgrades affect plugins, observers and preferences differently?

Plugins and observers depend on method names, signatures and event names, so an upgrade can break them when Adobe changes those contracts, which is why the compatibility checks and tests matter at every patch cycle. Preferences are riskier across upgrades because they replace whole classes, so any change to the original class in a new release must be carried into your copy by hand. Adobe's upgrade guide names customizations, extension count, third-party integrations and coding practices as drivers of upgrade effort. Ask for the upgrade test plan and a list of every customization point so each one can be checked against the new 2.4.x release line.

What drives the cost of an extension mechanism change?

Cost is driven mainly by three factors: the scope of the change, the number of overlapping modules that touch the same code, and the amount of automated test coverage already in place. A change to one method with no other extensions involved is a small analysis. A change where several modules plugin the same method, or where a preference is in play, requires tracing the full execution path and testing each combination. Low test coverage increases cost because each change needs manual verification. The fees are one-time for the design and build, while maintenance and retesting recur at each upgrade. Ask the provider to break the quote into analysis, build, test and handover so you can see where the effort sits.

How do we know which sort order resolves overlapping plugins?

Magento runs plugins on the same method in the order defined by the sortOrder attribute in each module's di.xml, with lower numbers running first. When two modules share a target method, the sort order determines which plugin sees the original arguments and which sees the result of the other. Confirm the order with the developer by listing every plugin on the method and its sort order, then test the outcome in staging with all extensions enabled. Changing sort order after a module is installed can change behavior in ways that only appear in specific flows, so treat it as a code change with its own tests.

How these choices affect upgrade effort

Adobe's upgrade guide names customizations, extension count, third-party integrations and coding practices as the main drivers of upgrade effort. Preferences are the most expensive of the three mechanisms to carry across an upgrade, because each one replaces a core class and the replacement must be reconciled with every core change to that class. A store with several preferences for the same class, or with preferences layered on top of extensions that also override it, multiplies the review work at each patch cycle. Before you approve a preference, ask whether a plugin or observer can achieve the same result, and record the answer in the change request.

Keep each override minimal. A plugin should wrap one method and call the original, a preference should exist only when no other mechanism can change the behavior, and every override should be documented in the module's README or a shared register with the class, the reason, the owning team and the extension that might conflict with it. Review the register before each upgrade, and confirm with your partner or internal team how the Upgrade Compatibility Tool results map to each entry. The register also shows which extensions already touch the same class, which is the first place to look when behavior changes after a patch.

Test sort order after every patch cycle, not only after major upgrades. Run bin/magento setup:di:compile on a staging copy, list the plugins registered for each intercepted method, and confirm that the sortOrder values in di.xml still produce the intended order when a vendor updates its extension. Check that observers still fire for the events your integrations depend on, and that no new preference has appeared in a dependency. Agree in the statement of work who runs these checks, what evidence is kept, and whether the test cases are handed over with the code.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.