O'Reilly logo

Magento 2 Developer's Guide by Branko Ajzele

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Configuring class preferences

A great number of Magento's core classes pass interfaces around constructors. The benefit of this is that the object manager, with the help of di.xml, can decide which class to actually instantiate for a given interface.

Let's imagine the Foggyline\Di\Console\Command\DiTestCommand class with a constructor, as follows:

public function __construct(
    \Foggyline\Di\Model\TestInterface $myArg1,
    $myArg2,
    $name = null
)
{
    //Method body here...
}

Note how $myArg1 is type hinted as the \Foggyline\Di\Model\TestInterface interface. The object manager knows that it needs to look into the entire di.xml for possible preference definitions.

We can define preference within the module's di.xml file, as follows:

<preference for="Foggyline\Di\Model\TestInterface" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required