24

So I noticed some Interceptor.php files in var/generation

I know that this folder contains generated classes created on the fly for the following:

  • Factories
  • Proxies
  • Plugins

I assume that Interceptor files are linked to the plugin ones however sometimes I don't get how those files are generated. For example I've got var/generation/Magento/Framework/App/Response/Http/Interceptor.php but this file don't seem to match any existing class.

So I'm looking for a well explained workflow on how Interceptor.php files are generated ?

32

Interceptor classes are an implementation of the interceptor design pattern. The interceptors are how how Magento 2's object system implements a plugin system.

As a client developer, the theory is you don't need to worry about interceptors -- you ask the object manager for an object of type X, and it returns it to you. The object you asked for may or may not be an interceptor, but from the client programmer point of view it behaves the same as the non-interceptor version. How the object manager decides to return or not return an interceptor in an implementation detail.

For people interested in that implementation detail -- if a class, or a parent class of that class, has a plugin configured, the object manager returns an interceptor. You can see that in the developer mode interceptor class here

#File: vendor/magento/framework/Interception/ObjectManager/Config/Developer.php
public function getInstanceType($instanceName)
{
    $type = parent::getInstanceType($instanceName);
    if ($this->interceptionConfig && $this->interceptionConfig->hasPlugins($instanceName)
        && $this->interceptableValidator->validate($instanceName)
    ) {
        return $type . '\\Interceptor';
    }
    return $type;
}

For production (i.e. compiled mode), Magento pre-scans the system during compilation mode, and makes a note of which classes need plugins.

As for the actual generation, Magento handles this with a PHP autoloader. If a developer instantiates a class (or otherwise triggers a PHP autoload event with a class name (in a type hint, class_exists class, etc), and the composer based autoloader can't find the class file, a second registered autoloader

Magento\Framework\Code\Generator\Autoloader::load

is triggered. This autoloader

vendor/magento/framework/Code/Generator/Autoloader.php

will (indirectly via the Magento\Framework\Code\Generator class) scan for the class for certain naming patterns. If the class name ends in Interceptor, Magento ends up generating an Interceptor via the generateClass method in this class

vendor/magento/framework/Code/Generator.php

There's additional classes/objects to trace out from the Magento\Framework\Code\Generator -- but we'll leave that as an exercise for the reader.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.