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="MagentoFrameworkMessageSessionStorage" type="MagentoFrameworkSessionStorage">
    <arguments>
        <argument name="namespace" xsi:type="string"> message</argument>
    </arguments>
</virtualType>
<type name="MagentoFrameworkMessageSession">
    <arguments>
        <argument name="storage" xsi:type="object"> MagentoFrameworkMessageSessionStorage</argument>
    </arguments>
</type>

The virtualType definition in the preceding example is MagentoFrameworkMessageSessionStorage, which extends from MagentoFrameworkSessionStorage and overwrites the namespace parameter to the message string value. In virtualType, the name attribute defines the globally unique name of the virtual type, while the type attribute matches the real PHP class that the virtual type is based on.

Now, if you look at the type definition, you will see that its storage argument is set to the object of MagentoFrameworkMessageSessionStorage. The SessionStorage file is actually a virtual type. This allows MessageSession to be customized without affecting other classes that also declare a dependency on SessionStorage.

Virtual types allow us to effectively change the behavior of a dependency when it is used in a specific class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.184.90