Another way to understand virtual types -
Let's say that you have a class \Class1
, which has the following constructor -
public function __construct(\Class2 $argOfClass1){...}
And \Class2
has the following constructor -
public function __construct(\Class3 $argOfClass2){...}
Now, you want to change the type of $argOfClass2
from \Class3
to \Class4
, but only when \Class2
is used as $argOfClass1
.
The "old" way to do that would be to add the following in di.xml
-
<type name="Class1">
<arguments>
<argument name="argOfClass1" xsi:type="object">Class5</argument>
</arguments>
</type>
where \Class5
is the following:
class \Class5 extends \Class2{
public function __construct(\Class4 $argOfClass2){...}
}
Instead of using this way, you can use the virtual types to accomplish the same, by adding the following to di.xml
:
<virtualType name="Class5" type="Class2">
<arguments>
<argument name="argOfClass2" xsi:type="string">Class4</argument>
</arguments>
</virtualType>
<type name="Class1">
<arguments>
<argument name="argOfClass1" xsi:type="object">Class5</argument>
</arguments>
</type>
As you can see, using the virtual type saved you the work of creation of Class5
.
For further reference I suggest to read Alan Storm's article regarding virtual types in Magento2 - http://alanstorm.com/magento_2_object_manager_virtual_types/
Practical way using magento2 module