Skip to content

ObjectManager and Plugins

torreytsui edited this page Apr 5, 2016 · 2 revisions

Magento 2 Dependency Injection provides interception.

Intercept before, around or after object creation

Define plugins and dependency injection on di.xml can intercepting the creation process, [before, around, or after] (https://github.com/magento/magento2/blob/develop/lib/internal/Magento/Framework/Interception/Interceptor.php#L118).

Example

The di.xml defines a VarnishPlugin to be executed around the creation of FrontControllerInterface

<type name="Magento\Framework\App\FrontControllerInterface">
    <plugin name="front-controller-varnish-cache" type="Magento\PageCache\Model\App\FrontController\VarnishPlugin"/>
</type>

VarnishPlugin::aroundDispatch executes during creation of FrontControllerInterface

    public function aroundDispatch(
        \Magento\Framework\App\FrontControllerInterface $subject,
        \Closure $proceed,
        \Magento\Framework\App\RequestInterface $request
    ) {
        $response = $proceed($request);
        if ($this->config->getType() == \Magento\PageCache\Model\Config::VARNISH && $this->config->isEnabled()
            && $response instanceof \Magento\Framework\App\Response\Http) {
            $this->version->process();
            if ($this->state->getMode() == \Magento\Framework\App\State::MODE_DEVELOPER) {
                $response->setHeader('X-Magento-Debug', 1);
            }
        }
        return $response;
    }

Intercept controller dispatch

Clone this wiki locally