Using virtual types

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> ...

Get Magento 2 Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.