How to get properly access to objectManager/entityCollection (products or categories for example) from custom API class ?
Should I use DI in constructor ?
Is this approach correct, or it breaks DI concept ?
<?php
namespace Company\Module\Model;
use Company\Module\Api\ModuleInterface;
class Connector implements ModuleInterface
{
protected $_objectManager;
public function __construct() {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$this->_objectManager = $objectManager;
}
public function myMethod(){
$productCollection = $this->_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
/** Apply filters here */
$productCollection->load();
}
}
Maybe someone can give the path to existing api in magento from which I can learn from ?
1 Answer 1
<?php
namespace Company\Module\Model;
use Company\Module\Api\ModuleInterface;
class Connector implements ModuleInterface
{
protected $collectionFactory;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
) {
$this->collectionFactory = $collectionFactory;
}
public function myMethod(){
$productCollection = $this->collectionFactory->create();
/** Apply filters here */
$productCollection->load();
}
}
answered Oct 31, 2016 at 21:34
Marius
199k55 gold badges431 silver badges837 bronze badges
default