Pergunta

I'm confused by Magento 2 documentation regarding plugins:

enter image description here

It is first said that:

Plugins cannot be used with virtual types

But then it is said that:

You can specify a class, interface, or virtual type as a type name which the plugin observes

Am I missing something or is the documentation contradicting itself ? Can we create plugins for virtual types ?

Foi útil?

Solução

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

Outras dicas

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top