Given a Scenario, Describe Usage of di.xml
Understanding Dependency Injection configuration, which is central to Magento's architecture.
di.xml Overview
The Concept of Dependency Injection (DI)
What is Dependency Injection?
Core Principle: A class is provided with the resources (other classes) it needs directly in its __construct method.
Magento uses Constructor Dependency Injection
- Classes don't call static methods or use
newkeyword - Classes simply declare what they need in the constructor
- Magento's DI system delivers the necessary instances automatically
Purpose and Location of di.xml
The di.xml configuration file instructs the Object Manager how to manage class dependencies.
File Locations
etc/di.xml
Applies to all areas
etc/adminhtml/di.xml
Admin panel only
etc/frontend/di.xml
Storefront only
What You Can Do with di.xml
- Substitute classes using preferences
- Create new classes with customized arguments using virtual types
- Change constructor arguments for a specific class using the type element
- Register custom routers
Key Usages
1. Preferences (<preference>)
Use: Substitute the requested class or interface (for) with a different concrete class (type).
<preference for="Magento\Catalog\Api\ProductRepositoryInterface"
type="Magento\Catalog\Model\ProductRepository" />
2. Type (<type>)
Use: Modify constructor arguments for a specific class.
<type name="Bonlineco\Blog\Model\PostRepository">
<arguments>
<argument name="pageSize" xsi:type="number">10</argument>
<argument name="defaultSort" xsi:type="string">created_at DESC</argument>
</arguments>
</type>
xsi:type values
string,boolean,number,array,object,const
3. Virtual Types (<virtualType>)
Use: Create a new configuration of an existing class with different constructor args.
<virtualType name="BonlinecoDebugLogger" type="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="name" xsi:type="string">bonlinecoDebug</argument>
</arguments>
</virtualType>
4. Plugins (Interceptors)
Plugins wrap public methods to run logic before/after/around them. Magento generates \Interceptor classes in generated/.
<type name="Magento\Catalog\Model\ProductRepository">
<plugin name="bonlineco_blog_product_plugin"
type="Bonlineco\Blog\Plugin\ProductRepositoryPlugin"
sortOrder="10" />
</type>
Exam Tips
Key Points
- Know the 3 locations for di.xml:
etc/,etc/adminhtml/,etc/frontend/ - Understand when to use
<preference>vs<type>vs<virtualType> - Remember all 6
xsi:typevalues - Preferences are global and conflict‑prone
- Plugins enable Interceptors and live in
generated/ - Magento uses constructor DI exclusively