5

From this documentation Factories are special objects that have only one purpose: to create an instance of one non-injectable class or interface non-injectable object are Objects that cannot be instantiated by the object manager. this \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory is a factory class that really exist in vendor/magento/catalog directory

why we should use this function instead of inject directly \Magento\Catalog\Model\ResourceModel\Category\Collection in constructor , and why \Magento\Catalog\Model\ResourceModel\Category\Collection is a none-injectable class because from this link it is not instance of entity to provide or a model representing a database entity it is a collection of models

and another question is why \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory already exist in vendor directory because from the documentation factories are an automatically generated class type. Factory classes do not need to be explicitly defined

1 Answer 1

6

In general you use factories to instantiate non-injectable objects, like the cms page object. Some objects require user input to instantiate so you cannot inject them via the constructor. \Magento\Catalog\Model\ResourceModel\Category\Collection is not one of those cases.

Factories are usually auto-generated, in the sense that, if you don't define one yourself, magento will auto-generate one for you:

if (!class_exists($className)) {
        return Generator::GENERATION_ERROR != $this->_generator->generateClass($className);
    }

And this answers your question about why you should use the Factory approach here. If you want to add a common behaviour for a certain collection, you have the chance to use your own Factory and easily modify the default behaviour.

But you can also inject \Magento\Catalog\Model\ResourceModel\Category\Collection in the constructor if you want to. This is not a case of a non-injectable object. It will still work, but it is not recommended.

2
  • thank u for your answer , as you mention If I want to add a common behaviour for a certain collection Factories are good , but can give an example for it , for example in my case what is the benefit of using \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory over \Magento\Catalog\Model\ResourceModel\Category\Collection
    – ali gh
    Jul 4, 2016 at 11:26
  • @aligh in your case I can't think of a benefit of using factories Jul 8, 2016 at 8:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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