2

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

2
<?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();
   }
}

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.