Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 42 ยท Dependency Injection

Preferences and Interfaces in di.xml

Learn how Magento 2 di.xml preferences map interfaces to classes, how to override core classes safely, how areas change them, and try a runnable stand-in.

The previous lesson showed that Magento classes ask for interfaces in their constructors. An interface cannot be instantiated, so something has to say which concrete class to use. That something is a preference declared in a di.xml file. Preferences are the simplest and most common piece of Magento's dependency injection configuration, and they are also how modules swap one implementation for another.

In this lesson you will read and write preferences, see how areas and module order decide the winner, learn why replacing a core class is a last resort, and run a stand-in resolver that behaves like a tiny di.xml merger. Real Magento XML is read-only; the runnable code is a plain-PHP imitation.

The preference node

A preference maps a requested type (the for attribute) to the type that should actually be built:

XML
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Acme\Greeting\Api\GreeterInterface"
                type="Acme\Greeting\Model\Greeter"/>
</config>

That file lives at app/code/Acme/Greeting/etc/di.xml. After it is in place, any class whose constructor asks for GreeterInterface receives an Acme\Greeting\Model\Greeter. A preference works on interfaces and on classes. Core Magento ships hundreds of them; for example, the core maps its logger and config-reader interfaces to concrete classes in this way.

This is the pattern behind service contracts, which you will meet in Service Contracts and Repositories: your module publishes an interface in Api/, ships one preference, and other code depends only on the interface.

flowchart LR
    A["Constructor asks for GreeterInterface"] --> B["Object Manager checks merged di.xml"]
    B --> C["preference: GreeterInterface to Model Greeter"]
    C --> D["Builds Greeter and its dependencies"]
    D --> E["Injects into your class"]

A preference turns the type that was asked for into the type that is built.

Where di.xml files live and who wins

Magento merges di.xml files from several places. Order matters because when two files prefer different classes for the same type, the one merged last wins:

  1. app/etc/di.xml: global configuration shipped with the framework.
  2. Each enabled module's etc/di.xml, merged in module load order (this is why the sequence setting from Module Sequence and Dependencies matters: a module that loads after another can override its preferences).
  3. Area-specific files, which are merged on top for requests in that area: etc/frontend/di.xml, etc/adminhtml/di.xml, etc/webapi_rest/di.xml, etc/graphql/di.xml and so on. They are covered in Areas and Configuration Files.

Area files let you change an implementation only where it makes sense. A module might use one price renderer on the storefront and another in the admin:

XML
<!-- etc/adminhtml/di.xml -->
<config>
    <preference for="Acme\Greeting\Api\GreeterInterface"
                type="Acme\Greeting\Model\AdminGreeter"/>
</config>

If your preference does not seem to apply, check three things: the file is in the right etc/ folder, your module is enabled and loaded after the module whose preference you want to beat, and the cache has been flushed (bin/magento cache:flush; in production mode also re-run setup:di:compile).

Overriding core classes, and why to be careful

Because a preference can point a class name at another class, you can replace a core class everywhere:

XML
<preference for="Magento\Catalog\Model\Product"
            type="Acme\Greeting\Model\Product"/>

Your replacement usually extends the original and overrides a method or two. It works, but it has real costs:

  • Only one winner. If two modules both prefer a different class for the same core class, only one is used, and the other module silently stops working.
  • Upgrade risk. Your subclass depends on the parent's constructor and internals, which can change between 2.4.x releases.
  • Constructor drift. Every change to the parent constructor must be mirrored in your child.

For these reasons the usual advice is: use a preference for interface-to-implementation wiring in your own module, and use a plugin (Plugins (Interceptors)) when you only want to change what a public method does. Plugins from many modules can coexist; preferences cannot.

Other di.xml nodes: type and arguments

Preferences are one of several di.xml node kinds. The type node configures how a class is built, most often by supplying constructor arguments:

XML
<type name="Acme\Greeting\Model\Greeter">
    <arguments>
        <argument name="defaultName" xsi:type="string">friend</argument>
    </arguments>
</type>

The name here is a class, and the argument name must match a constructor parameter name. type nodes can also declare <plugin> entries and set shared="false" to make a class non-shared. The virtualType node and the argument value types are the subject of the next lesson. Remember that type configures what is built when the class is requested, while preference decides which class is built in the first place.

A stand-in for preference resolution

The stand-in has a tiny DiConfig with a global layer and per-area layers. Resolving a type looks up the preference using the current area on top of the global layer, the way the merged configuration behaves. This is a model for learning, not the real implementation.

PHP Preferences with area overrides

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 frontend gets PlainGreeter and the admin gets AdminGreeter. After the "later module" call, the global preference changes to ShoutGreeter, but the area-specific preference still beats it in adminhtml, because area files are applied on top of the global configuration.

The next stand-in shows the failure mode of replacing a core class rather than using an interface: two modules fight over one class, and only the last registration remains.

PHP Two modules, one class, one winner

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.

A plugin chain avoids this problem, because both modules can add behavior to the same method. You will build one in the plugin lessons.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does <preference for="A" type="B"/> do?

    A preference maps the requested type to the type that is actually instantiated.
  2. 2. Two enabled modules prefer different classes for the same interface in their global di.xml. Which one is used?

    Only one preference exists per type after merging; the later file replaces the earlier one. Module sequence controls the load order.
  3. 3. Where would you put a preference that applies only to the admin panel?

    Area folders such as etc/adminhtml hold configuration that is merged on top of the global files only for that area.
  4. 4. Why is replacing a core class by preference usually a last resort?

    One winner per type and tight coupling to the parent's internals make class replacement fragile. Plugins let many modules cooperate.

Summary

  • A preference maps a requested interface or class to the type that should be built.
  • Preferences from all modules are merged; for the same for type the later one wins, so module order matters.
  • Area folders (etc/frontend, etc/adminhtml, ...) override global configuration only in that area.
  • Use preferences mainly for interface-to-implementation wiring; avoid replacing core classes when a plugin will do.
  • type nodes supply constructor arguments and plugins; preference chooses the class itself.
  • Flush the cache (and recompile in production mode) after changing di.xml.

Next: Virtual Types and Constructor Arguments