Magento 2 has a big 'depend on abstractions, not concretions' philosophy. One example of this is the use of Factories. Automatically generated factories.
But I'm wondering: from a software engineering point of view: what kind of classes would require factories. In my opinion factories are only required when it comes to data models or other kind of models that may or may not require persistence of some kind. For example:
- A (legacy) Model (like
- A data model (like
- A model that is not stored in the database but might provide functionality elsewhere (for example
Magento\Framework\Api\SortOrderFactoryto add sort orders to your search criteria).
However, in some cases, when persistency or dynamically generating objects is not required it makes no sense to have a factory. For example:
- Resource models (it makes no sense to create a resource model like
Magento\Catalog\Model\ResourceModel\ProductFactory::create()because resource models facilitate persistency and do not contain data).
- Helpers (basically global methods, don't contain data)
So my question for the community is: when do you decide when you need to use a factory or not?