Along with type
and preference
, there is another powerful feature of di.xml
that we can use. The virtualType
element enables us to define virtual types. Creating a virtual type is like creating a subclass of an existing class except for the fact that it's done in di.xml
and not in code.
Virtual types are a way of injecting dependencies into some of the existing classes without affecting other classes. To explain this via a practical example, let's take a look at the following virtual type defined in the app/etc/di.xml
file:
<virtualType name="Magento\Framework\Message\Session\Storage" type="Magento\Framework\Session\Storage"> <arguments> <argument name="namespace" xsi:type="string"> message</argument> </arguments> </virtualType> <type name="Magento\Framework\Message\Session"> <arguments> <argument name="storage" xsi:type="object"> Magento\Framework\Message\Session\Storage</argument>...