Magento 2: Virtual Class

Posted 8 months ago. Visible to the public.

Virtual Classes

The Virtual classes are not created physically with all features but it will be created by dependency injection file in magento 2.

Developers define these classes in di.xml when they want to use the existing classes with argument replacement to create additonal functionality without chaning the original class.

<virtualType name="MilestoneRepositoryExtended" type="Vasan\Training\Model\MilestoneRepository">
        <arguments>
            <argument name="milestoneManagement" xsi:type="object">Vasan\Training\Model\MilestoneManagementExtended</argument>
        </arguments>
    </virtualType>

In the above example, the milestoneManagement is the argument is replaced with extended functionality of the orginal.
The MilestoneRepositoryExtended class contains extended functionaliy of the MilestoneRepository.

Here we can use the MilestoneRepositoryExtended and MilestoneRepository when we want.

for example:

<type name="Vasan\Training\ViewModel\MilestoneView">
        <arguments>
            <argument name="milestoneRepository" xsi:type="object">MilestoneRepositoryExtended</argument>
        </arguments>
    </type>

The above declaration provided the extended functionaly to the view

vasan
Last edit
8 months ago
vasan
Posted by vasan to vasan's deck (2023-08-29 11:59)