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
public function getInstanceType($instanceName)
$type = parent::getInstanceType($instanceName);
if ($this->interceptionConfig && $this->interceptionConfig->hasPlugins($instanceName)
return $type . '\\Interceptor';
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
is triggered. This autoloader
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
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.