문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top