7

I am creating a custom module. which is preferred method to get collection. i need to know the advantage and disadvantage these method?

objectManager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$productCollection->load();

Factory

protected $_productCollectionFactory;

    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    ) {
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($data);
    }



    public function getProductCollection()
    {
        /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
        $collection = $this->_productCollectionFactory->create();
        return $collection;
    }
14

you should use the factory approach.
The advantage is: you may decide at one point to add some common behavior when a certain collection is retrieved. If the factory is autogenerated, you can just create your factory class and add the behavior in your code. This way, your factory will be used instead of the autogenerated class.
It's kind of similar to using getName method instead of getData('name').

The advantage of using the object manager is that you have to write less code, but this does not make it right.

7

Factories are special objects that have only one purpose: to create an instance of one non-injectable class or interface.

See more details in official documentation

2

Use Constructor Injection method, the second one..

Factory method is best practice to get the Collection, so use Factory Method.

However, at some places ObjectManager comes in hand as Constructor injection doesn't work for Collection (i.e: Observer classes)..

Rest is explained in KAndy's given official magento link.

1
  • 3
    "as Constructor injection doesn't work for Collection (i.e: Observer classes)" - what do you mean? What about \Magento\Framework\Event\ObserverFactory? – nevvermind May 1 '16 at 20:26
2

Use Factory Method are best manner to use instead of objectmanager in magento 2.

In core system magento 2, Most used are Factory methods instead of objectmanager.

You can using objectmanager concept while playing with root script or you haven't make any block for template file. you can directly call objectmanager.

But Factorymethod is proper way to use in magento 2 system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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