Generated Classes: Proxies

Continuing our look into Magento’s generated classes, we’re going to examine the neglected and oft forgotten sibling: the proxy!

Proxies are similar to interceptors in that they … intercept calls to a normal class’s public methods and “call through” to that original class. And yet they’re similar to factories in that they are generated when referenced explicitly. A proxy for the class MyVendor\MyModule\MyClass can be invoked with MyVendor\MyModule\MyClass\Proxy. (NOTE the backslash before Proxy, which is a different pattern than factories!)

But what are proxies for? These classes solve for unique scenarios in which merely instantiating a class (i.e., logic kicked off by its constructor) can potentially be resource intensive. It’s best not to create an instance of such a class until it’s necessary, and yet with dependency injection, the ship has sailed on instantiation before we even know what will be executed! Let’s look at an example:

If we imagine that someMethod is the only method of MyClass that uses SlowLoadingClass at all, then we can also imagine a scenario in which SlowLoadingClass is injected (and drags down performance) but ultimately unneeded.

Injecting SlowLoadingClass\Proxy instead solves the difficulty. A proxy class extends the original so that it fulfills type constraints, but it doesn’t actually rely on any parent calls and, in fact, doesn’t call through to the original constructor at all. Instead, it manages a separate instance of the original class that is only instantiated the first first time a public method call is actually made.

Unlike factories, proxies shouldn’t be referenced directly in PHP. To replace SlowLoadingClass in the constructor of MyClass above, we would leave the class definition as it is but replace slowLoader with di.xml:

Chris Nanninga

Director of Training and Development at SwiftOtter -@ChrisNanninga