In Magento 2, one of the new properties is Magento 2 Virtual Type. What are they for?
Imagine that you already have a class A available:
namespace VendorName\ModuleName\Model
class A
{
protected $arg1;
protected $arg2;
protected $arg3;
public function __construct(
Argument1 $arg1,
Argument2 $arg2,
Argument3 $arg3
) {
$this->arg1 = $arg1;
$this->arg2 = $arg2;
$this->arg3 = $arg3;
}
}
And you need to create a class B, which will be inherited from A. However, it must take another argument as $arg2. To do this, you will create a new PHP file for class B:
namespace Me\MyModule\Model
class B extends A
{
public function __construct(
Argument1 $arg1,
SomeOtherArg $someOtherArg,
Argument2 $arg3
) {
parent::__construct($arg1, $someOtherArg, $arg3)
} }
But you don't need to do this in Magento 2. In such cases, virtual types are created. Therefore, create the etc/di.xml file in your Magento module files and add the following code to it:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<virtualType name="Me\MyModule\Model\B" type="VendorName\ModuleName\Model\A">
<arguments>
<argument name="arg2" xsi:type="string">SomeOtherArg</argument>
</arguments>
</virtualType>
</config>
Regenerate DI using the command::
php bin/magento setup:di:compile
Now your can use the Me\MyModule\Model\B.
Explore more Magento 2 development tips and find out how to create basic Magento modules, custom cron, get store information and much more useful information.