Magento 2 – Practical Explanation of Proxy Class

dependency-injectiondimagento2PROXY

So, I know theorically what is a proxy class in Magento 2. I've read the awesome Alan Storm article about it and I totally understand how those classes are generated.

However, and I don't know if it's because I'm a non native English speaker or if Alan's explanations are using non core classes which are very abstract, but I'm having a hard time understanding how it works and specially when to use it during development.

So let's take this example from the core in app/code/Magento/GoogleAdwords/etc/di.xml:

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\GoogleAdwords\Observer\SetConversionValueObserver">
        <arguments>
            <argument name="collection" xsi:type="object">Magento\Sales\Model\ResourceModel\Order\Collection\Proxy</argument>
        </arguments>
    </type>
</config>

I would like to know:

  • why a proxy class is used in that particular case ?
  • when, in general, should one use a proxy class ?

Best Answer

This particular usage is not a good example of using Proxy pattern. I think it is even useless in that particular piece of code, as a collection is not doing any DB operations unless load method is called. If their observer would be used in console command class as the dependency, then it makes sense to use a proxy.

The proxy class should only be used when during construction of the object you execute an expensive operation. A good example is Symfony console commands:

Imagine your console command is using ProductRepository as a dependency. Product repository constructor establishes MySQL connection to catalog database.

It means on every bin/magento call, no matter which command you execute, the repository dependencies will be instantiated. So the only way to avoid it is to use lazy instantiation of original object by creating a proxy. In this case database, connection to catalog database will be established only when you call a repository method.

Hope that helps to understand the idea of proxy better.

Related Topic