Chiragit007
Chiragit007

Reputation: 1646

Difference between role of Interfaces and <type> in di.xml

I have one query regarding the understanding in role of interface <preference> and <type> attributes that are used in di.xml. Under which instances we should use <preference> and <type> ? Does there any solid difference in terms of logical implementation.

E.g go to app/code/Magento/Catalog/etc/di.xml, there would be lot of instances where <preference> and <type> tags are used. How exactly we can distinguish between them ?

Looking forward to hear thoughts.

Upvotes: 0

Views: 761

Answers (1)

Chris O&#39;Toole
Chris O&#39;Toole

Reputation: 1281

<preference> is used to indicate which concrete class you want the DI framework to supply when that type is requested.

<type> is used for a couple of different things, one of which is to supply or override arguments that are injected into the constructor of a concrete type. The <type> declaration is also used to declare plugins.

The time you see an interface in both the <preference> and the <type> is when a plugin is being defined for that interface. <type> allows you to declare a plugin on that object type, whether it is a concrete class or an interface.

Example from app/code/Magento/Catalog/etc/di.xml:

<preference for="Magento\Catalog\Api\ProductRepositoryInterface" type="Magento\Catalog\Model\ProductRepository" />
...
<type name="Magento\Catalog\Api\ProductRepositoryInterface">
    <plugin name="transactionWrapper" type="\Magento\Catalog\Model\Plugin\ProductRepository\TransactionWrapper" sortOrder="-1"/>
</type>

Upvotes: 1

Related Questions