type-virtualtype-magento

In the time of development or customization, you might have interacted with di.xml file. In di.xml files, you might have seen Type and Virtual Type nodes. The most common use while creating a UI component admin grid to provide the data to the component.

Let’s understand the difference between type and virtualType:

VirtualType

Virtual types are a way to inject different dependencies into existing classes without affecting other classes. Virtual Type must extend a concrete class type.

For example, the Magento\Framework\Session\Storage class takes a $namespace argument in its constructor, which defaults to the value ‘default’, and you could use the type definition to change the namespace to ‘core’.

<type name="Magento\Framework\Session\Storage">
    <arguments>
        <argument name="namespace" xsi:type="string">core</argument>
    </arguments>
</type>

The above code would make all the instances of Magento\Framework\Session\Storage
have a namespace of core.
Using the virtual type allows to creation a subclass equivalent to this class and only allows this subclass to use altered argument value rather than using that altered argument for all the instances that used this class.

<virtualType name="Magento\Core\Model\Session\Storage" type="Magento\Framework\Session\Storage">
    <arguments>
        <argument name="namespace" xsi:type="string">core</argument>
    </arguments>
</virtualType>

<type name="Magento\Framework\Session\Generic">
    <arguments>
        <argument name="storage" xsi:type="object">Magento\Core\Model\Session\Storage</argument>
    </arguments>
</type>

The first snippet creates a virtual type for Magento\Core\Model\Session\Storage which alters the namespace argument, and the second snippet injects the virtual type into Magento\Framework\Session\Generic. This allows Magento\Framework\Session\Generic to be customized without affecting other classes that also declare a dependency on Magento\Framework\Session\Storage
You can check more into the developer documentation of Magento for type and virtualType and also check di.xml file configuration.

I hope you like this post and be helpful in your daily coding routine.
If you want us to make a tutorial blog post about a particular topic comment below.

Rate this post