Magento 2 Virtual Type

Virtual type is really needed if you are running a virtual store based on the Magento 2 platform, the file di.xml supports for two types of nodes which are a node “type” and a node “virtualtype", meanwhile "virtualtype” is considered as a perfect method instead of the “type". The “virtual type" allows inserting different dependencies into the existing classes but not making any change to other classes.

Creating VirtualType in Magento 2

Creating virtualtype in Magento 2 means creating a sub-class for an existing class. You can create the virtualtype in Magento 2 in the following way.

<?php
class CustomVirtualTypeName extends \Magemeta\Virtual\Model\Virtualtype
{
}

The following script code is inserted to the module’s di.xml file to create a virtualtype in Magento 2.

#File: app/code/Magemeta/Virtual/etc/di.xml
<config>
    <!-- ... -->
    <virtualType name="customVirtualTypeName" type="Magemeta\Virtual\Model\Virtualtype">  
    </virtualType>        
</config>

The nodes are placed under the main config node and include two attributes: name and type. While the name attribute is mostly the universally special name of that node, the type attribute is the real PHP for the virtual type.

Using Virtual Type in Magento 2

The functionality of a virtual type is replacing the position of PHP classes and you would not have to use a configuration as the below if you wanted to inject the custom argument into the Magemeta class’s constructor.

#File: app/code/Magemeta/Virtual/etc/di.xml    
<config>
    <!-- ... -->
    <virtualType name="customVirtualTypeName" type="Magemeta\Virtual\Model\Virtualtype">  
    </virtualType>        

    <type name="Magemeta\Virtual\Model\Example">
        <arguments>
            <argument name="the_object" xsi:type="object">Some\Other\Class</argument>
        </arguments>
    </type>        

</config>

This means Some\Other\Class is recovered by customVirtualTypeName. You can ensure that no error is caused unless you call the command with the above in place.

#File: app/code/Magemeta/Virtual/etc/di.xml      
<config>
    <!-- ... -->
    <virtualType name="customVirtualTypeName" type="Magemeta\Virtual\Model\Virtualtype">  
    </virtualType>        

    <type name="Magemeta\Virtual\Model\Example">
        <arguments>
            <argument name="the_object" xsi:type="object">customVirtualTypeName</argument>
        </arguments>
    </type>        

</config>

Hope this helps you guys!

Leave a Reply