Question

When I overrided file controller of catalog/product and ran this command:

php bin/mangento setup:di:compile

And then this file "Interceptor.php" was generated in magento_root\var\generation\myPool\myModule\Controller\Adminhtml\Product\Initialization\Helper\Interceptor.php

Anyone, are you know? What is this file?

Was it helpful?

Solution

Magento 2 plugin system based on the Interceptor pattern. Calls to almost any module can be intercepted and altered. Vast improvement over the rewrite pattern in Magento 1, so obviously - no more rewrite conflict!

For example:

DI.xml

<config>
    <type name="{ObservedType}">
        <plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="false" />
    </type>
</config>

Sort order defines order if multiple plugins intercept the same item. It is possible to intercept before, after and around a function/method.

'Before' interceptor

class Plugin
{
    public function beforeSetName(\Magento\Catalog\Model\Product $subject, $name)
    {
        return array('(' . $name . ')');
    }
}

'After' interceptor

class Plugin
{
    public function afterGetName(\Magento\Catalog\Model\Product $subject, $name)
    {
        return array('|' . $name . '|');
    }
}

'Around' interceptor

class Plugin
{
    public function aroundSave(\Magento\Catalog\Model\Product $subject, \Closure $proceed, $name)
    {
        $this->doSomethingBeforeProductIsSaved();
        $returnValue = $proceed($name);
        if ($returnValue) {
            $this->postProductToFacebook($name);
        }
        return $returnValue;
    }
}

Checkout the Magento 2 sample module repo for a module that demonstrates interception.

Interceptors are replacement for rewrites. Interceptors supplement, but not replace events and observers.

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top