Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Today we’re going to explore the “class preference” feature of Magento 2’s object-manager/dependency-injection system. While this feature is a direct descendant of Magento 1’s class rewrite system, it ends up playing a different role in Magento 2. Where Magento 1’s class rewrites were aimed at allowing third party developers to customize system behavior, the class preference system is a core Magento 2 feature used to enforce a design by interface contract style of systems programming.

Here we see a similar pattern — the getMessage method calls the getHelloMessage method of the object in the message_holder property. The message_holder object contains an object that Magento creates via the __construct dependency injection system.

There is something different this time. The “object” that Magento injects is a Pulsestorm\TutorialObjectPreference\Model\MessageHolderInterface. Take a look at MessageHolderInterface‘s definition file

That’s no class, its a space station, PHP interface! If you’re not familiar with interfaces, we’ve written a short primer — but experienced PHP developers will know why we’re using exclamation points. You can’t instantiate a PHP interface — they’re not classes. So how is Magento injecting an interface?

Based on what we’ve learned about Magento’s object manager so far, you’re right to be confused. However, this is where the class preference feature comes into play.

Configuring Preferences for Classes

The first response to confusing code? Debugging with PHP’s reflection features, of course. Let’s try adding the following temporary var_dump debugging code to the Pulsestorm/TutorialObjectPreference/Model/Messenger‘s constructor.

So, we know that Magento injects a Pulsestorm\TutorialObjectPreference\Model\English, and that there’s not some unholy voodoo that allows us to actually instantiate an interface, (phew!) However, this does raise another question

Why is the object manager (via dependency injection), instantiating a Pulsestorm\TutorialObjectPreference\Model\English object when the type hint is for a Pulsestorm\TutorialObjectPreference\Model\MessageHolderInterface?

This is what the class preference system is — it’s a way for end users to configure which classes Magento’s object manager should actually use when the object manager requests a certain class/type (or, in the context of automatic dependency injection, encounters a specific type hint).

In the next section we’ll cover how to configure a class preference, but don’t forget to remove the temporary var_dump and exit above before we move on.

Configuring Class Preferences

Most (if not all?) of Magento’s object manager features are configured through a module’s etc/di.xml file. For a Magento 1 developer coming in new to Magento 2, the new system continues the work that was going on in later versions of Magento 1, and splits out feature specific configuration information into their own configuration files.

If you take a look at di.xml, you’ll see the following “top level” (under the real top level <config/>, that is) node.

This is the configuration node where we can set a class preference. In plain english, we’re telling the object manager that

When someone asks you to instantiate a Pulsestorm\TutorialObjectPreference\Model\MessageHolderInterface (the for attribute) you should actually instantiate a Pulsestorm\TutorialObjectPreference\Model\English object (the type attribute)

If we take a look at the definition for Pulsestorm\TutorialObjectPreference\Model\English, we’ll see our simple Hello message

By changing di.xml, we told the object manager to inject a different class/object. While this example is (obviously) simplified for pedagogical reasons, this is a powerful feature you can use to change the behavior of Magento 2 system wide.

Not Just Interfaces

Class preference configuration is not just for interfaces — you can change actual classes as well. Let’s jump back to our command definition file

You’ll recall Magento instantiates the Pulsestorm\TutorialObjectPreference\Model\Messenger object via automatic constructor dependency injection. Even though this is a concrete class, we can still change it. Try adding the following new<preference/> node to di.xml

This class is very similar to our Pulsestorm\TutorialObjectPreference\Model\Messsage2 class, with one exception: It doesn’t extend the original Pulsestorm\TutorialObjectPreference\Model\Message class. Let’s see what happens when we configure this class in di.xml (replacing the Message2 class)

$ php bin/magento ps:tutorial-object-preference
Autoload error: Argument 1 passed to
Pulsestorm\TutorialObjectPreference\Command\Testbed::__construct()
must be an instance of Pulsestorm\TutorialObjectPreference\Model\Messenger
instance of Pulsestorm\TutorialObjectPreference\Model\Messenger3 given,
called in
lib/internal/Magento/Framework/ObjectManager/Factory/AbstractFactory.php
on line 99 and defined ...

Curses — an error! However, this is a helpful error. What happened here was we successfully configured Messenger3 — but when Magento tried to inject it into the __construct method

this new class failed the type hint check, and PHP rejected the change. While this may seem annoying, it’s actually a good thing. The class preference system in Magento 2 has an added layer of type safety. In Magento 1 you could replace a class alias like Mage::getMode(catalog/product) with any PHP class you wanted — but if that class was missing a method, your project would fail, sometimes in mysterious “not immediately evident” ways.

Similarly, our previous English and Spanish classes each implemented the MessageHolderInterface

By using PHP’s built-in type hints for automatic dependency injection, Magento gets this added level of type safety for free. By forcing developers along a path where they’re required to use dependency injection to instantiate objects, Magento forces developers along this type-safe (or type-less-dangerous) path.

Once you’ve digested all this, you may be left with a lingering question

Is it better to use interfaces for all my injected dependencies, or should some be concrete class files?

While that’s a very good question, it’s a question without (at the moment) a clear answer. I will say, all other things being equal, it would be better to have an interface for any dependencies you’re injecting into the system, as an interface allows future developers more flexibility in building a replacement class for your dependency. Of course all things are never equal, and the true best practice will reveal itself after Magento 2 starts getting some real world use.

To Rewrite or Not Rewrite

While we’ve described the object manager’s class preference system as a replacement for the class rewrite system — and you can certainly use it as such — its real value comes from being a tool for developers interested in using design by contract style programming in their modules. By letting developers specify dependency injectable type hints that are interfaces, developers are (in turn) encouraged to use interfaces — knowing they can swap out their concrete implementations if they need to with a simple configuration change (as opposed to a complex refactoring).

There’s also another reason to look askance at the class preference feature as a replacement for class rewrites — and that’s because Magento’s object manager comes with a slew of other features that are both more powerful, and more specific, than the broad rewrite concept. We’ll explore more of these features in our next article, when we cover the configurable arguments feature of Magento 2’s object manager system.