I figured out that magento 2 uses a proxy class which then creates an instance of a class. I don't understand why this proxy class is used, whats the advantage of it? Why not just creating the instance normally like always?
Example:
vendor\magento\module-catalog\Model\Product\Link.php:
public function __construct(
...
\Magento\Catalog\Model\ResourceModel\Product\Link\Product\CollectionFactory $productCollectionFactory,
...
array $data = []
) {
...
$this->_productCollectionFactory = $productCollectionFactory;
...
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create()->setLinkModel($this);
return $collection;
}
The method create()
from $this->_productCollectionFactory->create()
is defined in generated\code\Magento\Catalog\Model\ResourceModel\Product\Link\Product\CollectionFactory.php:
public function create(array $data = [])
{
return $this->_objectManager->create($this->_instanceName, $data);
}
It uses objectManager to create the object from the class defined in $this->_instanceName
which is \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection
This looks totaly complicated and unecessary, why all this trouble? Why not just creating the object directly from start in the constructor:
public function __construct(
...
\Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection $productCollection,
...
array $data = []
) {
...
$this->_productCollection = $productCollection;
...
}
public function getProductCollection()
{
$collection = $this->_productCollection->setLinkModel($this);
return $collection;
}
Please help me to understand the advantage of the factory way.