4

I read here, there are two types of classes available in Magento 2. Injectible and Non-injectible.

To inject a non-injectible object as dependency, we use Factory Class.

For example

Magento\Catalog\Model\Product is non-injectible. That’s because it is a model that relies on data from the database. In order to be able to inject this as a dependency, we will use Factory Class.

But what is the purpose of Proxy Class and in which scenario, we need to use Proxy Class

What is the difference between them?

2 Answers 2

12

Proxy classes are intended to increase object creation speed. For example you want to create an object of the class where a lot of another classes are created in the constructor via dependency injection. Maybe you won't use those classes but they are created and some of them can take some time to be created.

To avoid such a scenario Proxy objects exists. The proxy object completely replaces the constructor of the proxied object, and does not make a parent::__construct call. In this way you avoid creation all the classes in the constructor. Instead Proxy objects have constructor with three parameters

public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager, $instanceName = '\\Pulsestorm\\TutorialProxy1\\Model\\SlowLoading', $shared = true)
{
    $this->_objectManager = $objectManager;
    $this->_instanceName = $instanceName;
    $this->_isShared = $shared;
}

The first is an object manager instance, the second is the name of the class this object proxies, and the third is a shared argument.

So, by replacing the entire constructor, we avoid any slow loading behavior.

Each method of original object is override by proxy object. Just string $this->_getSubject() is added that create instance of original object! In this way you call constructor of original object only when it's needed. Something like lazy loading.

Recommend you to read excellent post about proxy objects

1
  • Using proxies can optimize your application by only loading resources which are required. We don't need to create an object for each class which is passed to __construct().
    – akgola
    Mar 13, 2019 at 13:10
2

Proxy classes use for lazy creation of object (on first method call). See more information in official documentation

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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