O'Reilly logo

Magento 2 Developer's Guide by Branko Ajzele

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required