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" ...
Get Magento 2 Developer's Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.