Magento 2: virtual types plugins
No, plugins on virtual types do not work.
Proof of concept code:
<?php
namespace Training\Example\Model
class Type
{
public function bar()
{
return __CLASS__;
}
}
Plugin using <type>
:
<?php
namespace Training\Example\Model;
class TypePlugin
{
public function afterBar(Type $subject)
{
return __CLASS__;
}
}
Plugin using <virtualType>
:
<?php
namespace Training\Example\Model;
class VirtualTypePlugin
{
public function afterBar(Type $subject)
{
return __CLASS__;
}
}
DI config:
<?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="Foo" type="Training\Example\Model\Type">
<plugin name="myfoo" type="Training\Example\Model\VirtualTypePlugin"/>
</virtualType>
<type name="Foo">
<plugin name="yourfoo" type="Training\Example\Model\TypePlugin"/>
</type>
</config>
Test:
<?php
namespace Training\Example\Training\Integration;
use Magento\TestFramework\ObjectManager;
use Training\Example\Model\Type;
use Training\Example\Model\VirtualTypePlugin;
class VirtualTypePluginTest extends \PHPUnit_Framework_TestCase
{
public function testPluginsOnVirtualTypesWork()
{
/** @var Type $instance */
$instance = ObjectManager::getInstance()->create(Type::class);
$this->assertSame(VirtualTypePlugin::class, $instance->bar());
}
}
Result:
Failed asserting that two strings are identical.
Expected :Training\Example\Model\VirtualTypePlugin
Actual :Training\Example\Model\Type
Plugins will work for virtual type but only if you specify it for parent classes or interfaces, but you cannot specify plugin specific for concrete virtual type