di.xml file

Useful of di.xml a Dependency Injection in Magento 2

Posted by

Magento 2, renowned for its flexibility and extensibility, relies heavily on Dependency Injection (DI) to manage object dependencies. The di.xml file emerges as a key orchestrator in this intricate ballet of dependencies, providing a means to configure and customize the injection process. Let’s delve into the significance and functionality of the di.xml file.

Understanding Dependency Injection

At the heart of Magento 2’s architecture lies the concept of DI. Instead of hardcoding dependencies within a class, Magento leverages DI to inject dependencies from external sources, promoting modularity and maintainability.

Purpose of di.xml in Magento 2 modules

The di.xml file, residing in the etc directory of a module, serves as the configuration file for declaring preferences, virtual types, plugin and type configurations for dependency injection. The file can be present in 2 places of a module or only one place or not present at all. First where it reside is in module/etc, if the file is place in this directory then it will apply in all areas (store front, admin and api). Where as if the file is placed inside module/etc/adminhtml then it will apply changes only to the admin area.

1. Declaring Preferences:

In Magento, preferences define which class should be instantiated when an interface or a class is requested. The di.xml file is where you declare these preferences. This is also used when you want to override some of the class’s method which is not possible using a plugin class like a protected or private method. It is always recommended not to use preferences to override a method of a class if the method is public. Always prefer the plugin way to alter the method’s functionality.

<!-- Example: Declaring a preference -->
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Vendor\Module\Api\CustomInterface" type="Vendor\Module\Model\CustomImplementation" />
</config>

In the above example when the interface CustomInterface is instantiate in some class then that time it will instantiate a Vendor\Module\Model\CustomImplementation class.

2. Configuring Virtual Types:

Virtual types allow you to define a configuration that is used as a blueprint for creating other types. This promotes reusability and consistency in your codebase.

<!-- Example: Configuring a virtual type -->
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="CustomLogger" type="Psr\Log\LoggerInterface">
        <arguments>
            <argument name="name" xsi:type="string">custom_logger</argument>
            <argument name="handlers" xsi:type="array">
                <item name="system" xsi:type="object">Magento\Framework\Logger\Handler\System</item>
            </argument>
        </arguments>
    </virtualType>
</config>

3. Type Configurations:

The type element is where you can configure constructor arguments, method calls, and other settings for a specific class. These classes are configured in the di file, allowing developers to define constructor arguments, method calls, and other configurations for specific classes.

<!-- Example: Configuring a type -->
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Model\Product">
        <arguments>
            <argument name="customAttribute" xsi:type="string">custom_value</argument>
        </arguments>
    </type>
</config>

4. Plugin:

A plugin class is a powerful mechanism for extending or modifying the behaviour of public class methods without directly altering their code. Also known as interceptors, plugins enable developers to inject custom code before, after, or around the execution of a specific method. This allows for seamless customization of Magento core functionalities or third-party extensions without the need for extensive rewrites.

<!-- Example: Configuring a Plugin class-->
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Ui\Component\Product\MassAction">
        <plugin name="sort_actions" type="Learningmagento\Duplicate\Plugin\Component\MassAction"/>
    </type>
</config>
Class MassAction
<?php

namespace Learningmagento\Duplicate\Plugin\Component;

use Magento\Framework\App\RequestInterface;
use Learningmagento\Duplicate\Helper\Configuration;

/**
 * Class MassAction
 */class MassAction
{
    /** @var RequestInterface */    protected $_request;

    /**
     * @var Configuration
     */    protected $configuration;

    /**
     * MassAction constructor.
     * @param RequestInterface $request
     */    public function __construct(
        RequestInterface  $request,
        Configuration $configuration
    ) {
        $this->_request = $request;
        $this->configuration = $configuration;
    }

    /**
     * Method to modifiy existing functionality
     *
     * @param ComponentMassAction $massAction
     */    public function afterPrepare(\Magento\Catalog\Ui\Component\Product\MassAction $massAction)
    {
        /** Code you want to place to edit **/    }
}

The above class Learningmagento\Duplicate\Plugin\Component\MassAction is a plugin class for Magento\Catalog\Ui\Component\Product\MassAction. The class has a method name afterPrepare(). This is an after method which will run after the method prepare() inside Magento\Catalog\Ui\Component\Product\MassAction to alter its output.

Leveraging DI for Customization

Understanding the nuances of di empowers developers to extend and customize Magento 2 with precision. Whether it’s altering class preferences, configuring virtual types, or fine-tuning type configurations, di.xml is the go-to tool for achieving a seamless and modular codebase in Magento 2. Check the official documentation about DI configuration on adobe website. To learn more about Adobe commerce | Magento development. Checkout our development category.