Edit in GitHubLog an issue

Dependency injection configuration

The di.xml file configures which dependencies are injected by the object manager. You can also specify sensitive configuration settings using di.xml.

Areas and application entry points#

Each module can have a global and area-specific di.xml file. The application reads all the di.xml configuration files declared in the system and merges them all together by appending all nodes.

As a general rule, the area specific di.xml files should configure dependencies for the presentation layer, and your module's global di.xml file should configure the remaining dependencies.

The application loads the configuration in the following stages:

  1. Initial (app/etc/di.xml)
  2. Global (<moduleDir>/etc/di.xml)
  3. Area-specific (<moduleDir>/etc/<area>/di.xml)

The areas are:

  • adminhtml
  • frontend
  • graphql
  • webapi_rest
  • webapi_soap
  • crontab

During bootstrapping, each application entry point loads the appropriate di.xml files for the requested area.


In index.php, the \Magento\Framework\App\Http class loads the area based on the front-name provided in the URL.

Copied to your clipboard
1$areaCode = $this->_areaList->getCodeByFrontName($this->_request->getFrontName());

In static.php, the \Magento\Framework\App\StaticResource class also loads the area based on the URL in the request.

Copied to your clipboard
1$path = $this->request->get('resource');
2$params = $this->parsePath($path);

In cron.php, the \Magento\Framework\App\Cron class always loads the crontab area.

Copied to your clipboard
2$configLoader = $this->objectManager->get(\Magento\Framework\ObjectManager\ConfigLoaderInterface::class);

Type configuration#

Type configurations describe an object's lifestyle and how to instantiate it.

You can configure the type in your di.xml configuration node in the following ways:

Copied to your clipboard
1<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
2 <virtualType name="moduleConfig" type="Magento\Core\Model\Config">
3 <arguments>
4 <argument name="type" xsi:type="string">system</argument>
5 </arguments>
6 </virtualType>
7 <type name="Magento\Core\Model\App">
8 <arguments>
9 <argument name="config" xsi:type="object">moduleConfig</argument>
10 </arguments>
11 </type>

The preceding example declares the following types:

  • moduleConfig: A virtual type that extends the type Magento\Core\Model\Config.
  • Magento\Core\Model\App: All instances of this type receive an instance of moduleConfig as a dependency.

Virtual types#

A virtual type allows you to change the arguments of a specific injectable dependency and change the behavior of a particular class. This allows you to use a customized class without affecting other classes that have a dependency on the original.

The example creates a virtual type for Magento\Core\Model\Config and specifies system as the constructor argument for type.

Constructor arguments#

You can configure the class constructor arguments in your di.xml in the argument node. The object manager injects these arguments into the class during creation. The name of the argument configured in the XML file must correspond to the name of the parameter in the constructor in the configured class.

The following example creates instances of Magento\Core\Model\Session with the class constructor argument $sessionName set to a value of adminhtml:

Copied to your clipboard
1<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
2 <type name="Magento\Core\Model\Session">
3 <arguments>
4 <argument name="sessionName" xsi:type="string">adminhtml</argument>
5 </arguments>
6 </type>

Argument types#


Node Formats:

<argument xsi:type="object">{typeName}</argument> <argument xsi:type="object" shared="{shared}">{typeName}</argument>

Creates an instance of typeName type and passes it in as an argument. You can pass any class name, interface name, or virtual type as typeName.

Setting the shared property defines the lifestyle of a created instance. See object lifestyle configuration.


Node Formats:

<argument xsi:type="string">{strValue}</argument> <argument xsi:type="string" translate="true">{strValue}</argument>

The application interprets any value for this argument node as a string.


Node Format:

<argument xsi:type="boolean">{boolValue}</argument>

The application converts any value for this argument node into a boolean value. See table below:

Input TypeDataBoolean Value
*These String literals are case-sensitive


Node Format:

<argument xsi:type="number">{numericValue}</argument>

Acceptable values for this type include: integers, floats, or numeric strings.


Node Format:

<argument xsi:type="init_parameter">{Constant::NAME}</argument>

This is the global application initialization argument represented by Constant::NAME.


Node Format:

<argument xsi:type="const">{Constant::NAME}</argument>

This is the constant value represented by Constant::NAME.


Node Format:

<argument xsi:type="null"/>

This indicates a null value.


Node Format:

The node format is as follows:

Copied to your clipboard
1<argument xsi:type="array">
2 <item name="someKey" xsi:type="<type>">someVal</item>

The application builds an array with elements corresponding to the items and passes it as the argument. The array can contain an infinite number of items, and each array item can be of any object type including an array itself.

When the application merges the configuration files for a given scope, array arguments with the same name get merged into a new array.

When the application loads a new configuration at a later time, either by a more specific scope or through code, then any array definitions in the new configuration will replace the loaded config instead of merging.

Argument Examples:

Copied to your clipboard
1<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
2 <type name="Magento\Example\Type">
3 <arguments>
4 <!-- Pass simple string -->
5 <argument name="stringParam" xsi:type="string">someStringValue</argument>
6 <!-- Pass instance of Magento\Some\Type -->
7 <argument name="instanceParam" xsi:type="object">Magento\Some\Type</argument>
8 <!-- Pass true -->
9 <argument name="boolParam" xsi:type="boolean">1</argument>
10 <!-- Pass 1 -->
11 <argument name="intParam" xsi:type="number">1</argument>
12 <!-- Pass application init argument, named by constant value -->
13 <argument name="globalInitParam" xsi:type="init_parameter">Magento\Some\Class::SOME_CONSTANT</argument>
14 <!-- Pass constant value -->
15 <argument name="constantParam" xsi:type="const">Magento\Some\Class::SOME_CONSTANT</argument>
16 <!-- Pass null value -->
17 <argument name="optionalParam" xsi:type="null"/>
18 <!-- Pass array -->
19 <argument name="arrayParam" xsi:type="array">
20 <!-- First element is value of constant -->
21 <item name="firstElem" xsi:type="const">Magento\Some\Class::SOME_CONSTANT</item>
22 <!-- Second element is null -->
23 <item name="secondElem" xsi:type="null"/>
24 <!-- Third element is a subarray -->
25 <item name="thirdElem" xsi:type="array">
26 <!-- Subarray contains scalar value -->
27 <item name="scalarValue" xsi:type="string">ScalarValue</item>
28 <!-- and application init argument -->
29 <item name="globalArgument " xsi:type="init_parameter">Magento\Some\Class::SOME_CONSTANT</item>
30 </item>
31 </argument>
32 </arguments>
33 </type>

Abstraction-implementation mappings#

The object manager uses abstraction-implementation mappings when the constructor signature of a class requests an object by its interface. The object manager uses these mappings to determine what the default implementation is for that class for a particular scope.

The preference node specifies the default implementation:

Copied to your clipboard
1<!-- File: app/etc/di.xml -->
3 <preference for="Magento\Framework\UrlInterface" type="Magento\Framework\Url" />

This mapping is in app/etc/di.xml, so the object manager injects the Magento\Framework\Url implementation class wherever there is a request for the Magento\Framework\UrlInterface in the global scope.

Copied to your clipboard
1<!-- File: app/code/Magento/Backend/etc/adminhtml/di.xml -->
3 <preference for="Magento\Framework\UrlInterface" type="Magento\Backend\Model\UrlInterface" />

This mapping is in app/code/Magento/Backend/etc/adminhtml/di.xml, so the object manager injects the Magento\Backend\Model\UrlInterface implementation class wherever there is a request for the Magento\Framework\UrlInterface in the admin area.

Override a method using 'preference' nodes#

If you want to override a public or protected method from a core class, utilize the preference node from di.xml to achieve it. Here is an example of overriding a method from a core file:

Copied to your clipboard
1<!-- app/code/ExampleCorp/OverrideExample/etc/di.xml -->
2<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
3 <preference for="Magento\Checkout\Block\Onepage\Success" type="ExampleCorp\OverrideExample\Block\Onepage\Success" />

The example below overrides the isVisible method from the Magento\Checkout\Block\Onepage\Success block class.

Copied to your clipboard
3 * Copyright © Magento, Inc. All rights reserved.
4 * See COPYING.txt for license details.
5 */
7namespace ExampleCorp\OverrideExample\Block\Onepage;
9use Magento\Checkout\Block\Onepage\Success as MagentoSuccess;
10use Magento\Framework\View\Element\Template\Context;
11use Magento\Checkout\Model\Session;
12use Magento\Sales\Model\Order\Config;
13use Magento\Framework\App\Http\Context as HttpContext;
15class Success extends MagentoSuccess
17 /**
18 * Constructor Modification
19 *
20 * @param Context $context
21 * @param Session $checkoutSession
22 * @param Config $orderConfig
23 * @param HttpContext $httpContext
24 * @param array $data
25 */
26 public function __construct(
27 Context $context,
28 Session $checkoutSession,
29 Config $orderConfig,
30 HttpContext $httpContext,
31 array $data = []
32 ) {
33 parent::__construct(
34 $context,
35 $checkoutSession,
36 $orderConfig,
37 $httpContext,
38 $data
39 );
40 }
42 /**
43 * Is order visible
44 *
45 * @param Order $order
46 * @return bool
47 */
48 protected function isVisible(Order $order)
49 {
50 # Write your custom logic here.
51 return !in_array(
52 $order->getStatus(),
53 $this->_orderConfig->getInvisibleOnFrontStatuses()
54 );
55 }

Parameter configuration inheritance#

Parameters configured for a class type pass on its configuration to its descendant classes. Any descendant can override the parameters configured for its supertype; that is, the parent class or interface:

Copied to your clipboard
1<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
2 <type name="Magento\Framework\View\Element\Context">
3 <arguments>
4 <argument name="urlBuilder" xsi:type="object">Magento\Framework\Url</argument>
5 </arguments>
6 </type>
7 <type name="Magento\Backend\Block\Context">
8 <arguments>
9 <argument name="urlBuilder" xsi:type="object">Magento\Backend\Model\Url</argument>
10 </arguments>
11 </type>

In the preceding example, Magento\Backend\Block\Context is a descendant of Magento\Framework\View\Element\Context.

The first entry configures all instances of Magento\Framework\View\Element\Context as well as its children to pass in Magento\Framework\Url as $urlBuilder in their constructors.

The second entry overrides this and configures all instances of Magento\Backend\Block\Context to use Magento\Backend\Model\Url as the $urlBuilder instead.

Object lifestyle configuration#

The lifestyle of an object determines the number of instances that can exist of that object.

You can configure dependencies in Adobe Commerce and Magento Open Source to have the following lifestyles:

  • Singleton(default) - One instance of this class exists. The object manager creates it at the first request. Requesting the class again returns the same instance. Disposing or ending the container registered to it releases the instance.
  • Transient - The object manager creates a new instance of the class for every request.

The shared property determines the lifestyle of both argument and type configurations.

Copied to your clipboard
1<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
2 <type name="Magento\Filesystem" shared="false">
3 <arguments>
4 <argument name="adapter" xsi:type="object" shared="false">Magento\Filesystem\Adapter\Local</argument>
5 </arguments>
6 </type>

In this example Magento\Filesystem is not shared, so all clients will retrieve separate instances of Magento\Filesystem. Also, every instance of Magento\Filesystem will get separate instance of $adapter, because it is non-shared too.

Sensitive and system-specific configuration settings#

For multi-system deployments, such as the pipeline deployment model, you can specify the following types of configuration settings:

sharedSettings that are shared between systems using app/etc/config.php
sensitiveSettings that are restricted or confidential
system-specificSettings that are unique to a particular system or environment

The following code sample is a template for specifying values as sensitive or system-specific:

Copied to your clipboard
1<type name="Magento\Config\Model\Config\TypePool">
2 <arguments>
3 <argument name="VALUE_TYPE" xsi:type="array">
4 <item name="CONFIG_PATH" xsi:type="string">ARGUMENT_VALUE</item>
5 </argument>
6 </arguments>
VALUE_TYPESpecifies the type of value: either sensitive or environment.
CONFIG_PATHA unique, /-delimited string that identifies this configuration setting.
ARGUMENT_VALUEA value of 1 indicates the CONFIG_PATH value is sensitive or system-specific. The default 0 value indicates it is neither sensitive nor system specific.

Do not share sensitive or system-specific settings stored in app/etc/env.php between development and production systems.

See sensitive and environment settings for more information and examples.

Information related to pipeline deployment#

Get dependency injection configuration information for a class#

Use the dev:di:info command to retrieve information about dependency injection configuration for a class. The following example retrieves the dependency injection configuration information for the Magento\Quote\Model\Quote\Item\ToOrderItem class:

Copied to your clipboard
bin/magento dev:di:info "Magento\Quote\Model\Quote\Item\ToOrderItem"
Copied to your clipboard
1DI configuration for the class Magento\Quote\Model\Quote\Item\ToOrderItem in the GLOBAL area
3Preference: Magento\Quote\Model\Quote\Item\ToOrderItem
5Constructor Parameters:
7| Name | Requested Type | Configured Value |
9| orderItemFactory | Magento\Sales\Api\Data\OrderItemInterfaceFactory | |
10| objectCopyService | Magento\Framework\DataObject\Copy | |
11| dataObjectHelper | Magento\Framework\Api\DataObjectHelper | |
16| Plugin | Method | Type |
18| Magento\Catalog\Model\Plugin\QuoteItemProductOption | convert | before |
19| Magento\GiftMessage\Model\Plugin\QuoteItem | convert | after |
20| Magento\Bundle\Model\Plugin\QuoteItem | convert | after |
23Plugins for the Preference:
25| Plugin | Method | Type |
27| Magento\Catalog\Model\Plugin\QuoteItemProductOption | convert | before |
28| Magento\GiftMessage\Model\Plugin\QuoteItem | convert | after |
29| Magento\Bundle\Model\Plugin\QuoteItem | convert | after |
Was this helpful?
  • Privacy
  • Terms of Use
  • Do not sell my personal information
  • AdChoices
Copyright © 2022 Adobe. All rights reserved.