Generated Classes: Interceptors

In this series of knowledge bites, we’re going to look at the different kinds of auto-generated classes in Adobe Commerce and Magento Open Source. Auto-generated classes are created on the fly as needed in environments in “developer” mode, or comprehensively with the DI compilation process in environments in “production” mode, and they are critical to several architectural features. We’ll first be examining interceptors.

Interceptors are one of the “passive” generated classes in Magento, in that they aren’t utilized by directly invoking them, but are generated under the hood to accommodate plugins. Plugins allow targeted and unobtrusive changes to the behavior of public methods from outside the original class, but generated PHP code is necessary to make this possible.

In a typical call to a public method, the class being invoked has full control over execution until the method is complete:

In order for plugins to hook in and modify such a method, an interceptor class that extends and replaces the original is generated. All public methods on the interceptor invoke the plugins system, allowing outside code to manipulate input or output; the original class method is ultimately called by the plugin logic (assuming it’s not canceled by an around plugin).

Interceptors are automatically generated for any class that has plugins defined.

You’re not likely to deal directly with interceptors frequently, but understanding them is highly valuable, particularly for debugging. If you’re stepping through code execution and find yourself in an interceptor method, the experience can be quite mystifying if you haven’t familiarized yourself with how the plugin system works. A look into \Magento\Framework\Interception\Interceptor::___callPlugins, in particular, will give you a great deal of insight into the plugin execution cycle.

Chris Nanninga

Director of Training and Development at SwiftOtter -@ChrisNanninga