Skip to content
intermediate Phase 27 · DI Fundamentals

di.xml Deep Dive

Comprehensive guide to Magento 2 di.xml: type arguments, init_arguments, shared flag, cleanup, area-specific DI, and advanced configurations

1h
0 problems
Topic Progress 0%

Type Arguments Configuration

Basic Arguments

<type name="Amazon\Prep\Service\WarrantyService">
    <arguments>
        <!-- Scalar types -->
        <argument name="apiKey" xsi:type="string">sk_live_abc123</argument>
        <argument name="timeout" xsi:type="number">30</argument>
        <argument name="debug" xsi:type="boolean">false</argument>

        <!-- Object injection -->
        <argument name="logger" xsi:type="object">Psr\Log\NullLogger</argument>

        <!-- Array -->
        <argument name="options" xsi:type="array">
            <item name="max_retries" xsi:type="number">3</item>
            <item name="cache_ttl" xsi:type="number">3600</item>
        </argument>
    </arguments>
</type>

Argument Types

xsi:type PHP Type Example
string string 'value'
number int/float 30
boolean bool true
object class/interface ClassName
array array <item>...</item>
null null N/A
const constant CONSTANT_NAME
init_array array Used in init_arguments
init_string string Used in init_arguments

Complex Array Arguments

<type name="Amazon\Prep\Model\Config">
    <arguments>
        <argument name="shipping_methods" xsi:type="array">
            <item name="flat" xsi:type="array">
                <item name="label" xsi:type="string">Flat Rate</item>
                <item name="price" xsi:type="number">5.99</item>
                <item name="enabled" xsi:type="boolean">true</item>
            </item>
            <item name="free" xsi:type="array">
                <item name="label" xsi:type="string">Free Shipping</item>
                <item name="price" xsi:type="number">0</item>
                <item name="min_order" xsi:type="number">50</item>
            </item>
        </argument>
    </arguments>
</type>

Overriding Arguments

<!-- Child area overrides parent -->
<type name="Service">
    <arguments>
        <argument name="timeout" xsi:type="number">60</argument>  <!-- Override -->
        <argument name="newArg" xsi:type="string">value</argument>  <!-- Add -->
    </arguments>
</type>

Remove Arguments

<type name="Service">
    <arguments>
        <argument name="optionalArg" xsi:type="null"/>
    </arguments>
</type>

init_arguments Configuration

What is init_arguments?

init_arguments are called AFTER the object is constructed. They invoke methods on the created object.

<type name="Amazon\Prep\Model\Warranty">
    <arguments>
        <argument name="name" xsi:type="string">Default Warranty</argument>
    </arguments>
    <object name="init_arguments">
        <argument name="setData" xsi:type="array">
            <item name="status" xsi:type="string">active</item>
            <item name="created_by" xsi:type="string">system</item>
        </argument>
    </object>
</type>

How init_arguments Work

1. Object is constructed with constructor arguments
2. For each method in init_arguments:
   a. Method is called on the object
   b. Arguments are passed to the method

Complete Example

// Model class
class Warranty extends AbstractModel
{
    public function __construct(
        Context $context,
        Registry $registry,
        array $data = []
    ) {
        parent::__construct($context, $registry, $data);
    }

    public function setData(array $data): Warranty
    {
        // Called by init_arguments
        return parent::setData($data);
    }
}

XML configuration:

<type name="Amazon\Prep\Model\Warranty">
    <object name="init_arguments">
        <argument name="setData" xsi:type="array">
            <item name="status" xsi:type="string">active</item>
            <item name="is_default" xsi:type="boolean">true</item>
        </argument>
    </object>
</type>

init_arguments vs Constructor Arguments

Aspect Constructor Args init_arguments
Timing During construction After construction
Target Constructor parameters Method calls
Use case Dependencies Default state
Method __construct() Any public method

Shared Flag and Cleanup

shared Attribute

<!-- Default behavior (shared) -->
<type name="Amazon\Prep\Service\WarrantyService"/>

<!-- Explicitly non-shared -->
<type name="Amazon\Prep\Model\Warranty" shared="false"/>

<!-- Override to shared -->
<type name="Amazon\Prep\Helper\Data" shared="true"/>

When to Use Non-Shared

<!-- Models: always new instance -->
<type name="Amazon\Prep\Model\Warranty" shared="false"/>
<type name="Amazon\Prep\Model\WarrantyFactory" shared="false"/>

<!-- Collections: always new instance -->
<type name="Amazon\Prep\Model\ResourceModel\Warranty\Collection" shared="false"/>

<!-- Data objects: always new instance -->
<type name="Amazon\Prep\Model\Data\Warranty" shared="false"/>

Cleanup Configuration

Remove type configuration entirely:

<!-- Remove all arguments for a type -->
<type name="Amazon\Prep\Service\WarrantyService">
    <object name="cleanup"/>
</type>

Cleanup Specific Arguments

<type name="Amazon\Prep\Service\WarrantyService">
    <arguments>
        <!-- Remove specific argument -->
        <argument name="apiKey" xsi:type="null"/>
    </arguments>
</type>

Reset to Defaults

<!-- Reset all arguments to defaults -->
<type name="Amazon\Prep\Service\WarrantyService" reset="true"/>

Shared Instances in Memory

// Shared instances are stored in ObjectManager's registry
// They persist for the request lifecycle

// To reset shared instances (rarely needed):
$objectManager = ObjectManager::getInstance();
$objectManager->removeSharedInstance(Service::class);

Area-Specific DI

Area-Specific Files

etc/di.xml                 (global - all areas)
etc/frontend/di.xml       (frontend only)
etc/adminhtml/di.xml      (admin only)
etc/crontab/di.xml        (cron only)
etc/webapi/rest/di.xml    (REST API only)
etc/webapi/soap/di.xml    (SOAP API only)

Frontend-Specific DI

<!-- etc/frontend/di.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Amazon\Prep\Service\WarrantyService">
        <arguments>
            <argument name="enableCache" xsi:type="boolean">true</argument>
            <argument name="pageSize" xsi:type="number">20</argument>
        </arguments>
    </type>

    <!-- Frontend-only plugin -->
    <type name="Magento\Catalog\Model\Product">
        <plugin name="frontend_warranty" type="Amazon\Prep\Plugin\FrontendProductPlugin"/>
    </type>
</config>

Admin-Specific DI

<!-- etc/adminhtml/di.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Amazon\Prep\Service\WarrantyService">
        <arguments>
            <argument name="enableCache" xsi:type="boolean">false</argument>
            <argument name="pageSize" xsi:type="number">50</argument>
        </arguments>
    </type>

    <!-- Admin-only plugin -->
    <type name="Magento\Catalog\Model\Product">
        <plugin name="admin_warranty" type="Amazon\Prep\Plugin\AdminProductPlugin"/>
    </type>
</config>

REST API-Specific DI

<!-- etc/webapi/rest/di.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Amazon\Prep\Api\WarrantyRepositoryInterface">
        <plugin name="api_warranty" type="Amazon\Prep\Plugin\ApiWarrantyPlugin"/>
    </type>
</config>

Configuration Merge Order

1. Vendor/magento/module-*/etc/di.xml (core)
2. app/code/Vendor/Module/etc/di.xml (global)
3. app/code/Vendor/Module/etc/frontend/di.xml (area)

Later configurations override earlier ones for the same arguments.

Quiz

1. What is the difference between constructor arguments and init_arguments?

Question 1 options

2. Which di.xml file applies only to the frontend area?

Question 2 options

3. How do you remove a specific argument from di.xml?

Question 3 options

Flashcards

Question

What are init_arguments?

Answer

Methods called on an object after construction, used for default state setup

Question

How do you make a type non-shared?

Answer

Set shared="false" on the <type> element

Question

What area-specific di.xml files exist?

Answer

frontend, adminhtml, crontab, webapi/rest, webapi/soap

Question

How do you reset all arguments for a type?

Answer

Use reset="true" on the <type> element

Question

What is the configuration merge order?

Answer

Core di.xml → Module di.xml → Area di.xml

Revision Notes

Key Takeaways

  • 1. Type arguments configure constructor parameters in di.xml
  • 2. init_arguments call methods after object construction
  • 3. shared='false' forces new instances; default is shared (singleton)
  • 4. Area-specific di.xml files override global configurations
  • 5. Use reset='true' to clear all arguments for a type

Interview Tips

  • Explain the difference between arguments and init_arguments
  • Know how area-specific DI works and when to use it
  • Be ready to troubleshoot DI configuration issues
  • Discuss shared vs non-shared instance trade-offs

Cheat Sheet

Arguments:
  <argument name="key" xsi:type="string">value</argument>
  xsi:type: string, number, boolean, object, array, null

init_arguments:
  <object name="init_arguments">
    <argument name="methodName" xsi:type="array">...</argument>
  </object>

Shared: shared="false" on <type>
Area: etc/frontend/di.xml, etc/adminhtml/di.xml
Reset: reset="true" on <type>