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 Magento\Customer\Model\Customer).
  • A data model (like Magento\Customer\Model\Data\Customer).
  • A model that is not stored in the database but might provide functionality elsewhere (for example Magento\Framework\Api\SortOrderFactory to 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)
  • Repositories
  • Management-classes
  • etc.

So my question for the community is: when do you decide when you need to use a factory or not?


Basically by one question:

Does the object have (non-global) state?

If yes, use a factory.

What's non-global state?

  • constructor dependencies that are declared with shared=false in di.xml
  • constructor dependencies that you need to pass at runtime with create(['parameterName' => $value])
  • properties that can be changed. Here you should distinguish from case to case: some properties are just used to cache results of other operations that you want to be shared globally.
  • Could you provide some examples with your answer? – Giel Berkers Aug 3 '17 at 11:01
  • I clarified the term "non-global state" a bit, hope that helps – Fabian Schmengler Aug 3 '17 at 11:56
  • Thanks! Didn't know about the shared=false option. Seems to be used with caution ;-) – Giel Berkers Aug 3 '17 at 12:11

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.