I have some confusion while use Factory pattern vs new instance object.

What difference between them?

$object = objectManager->create() vs objectManager->create('ObjectFactory')

what benefits in cases when create object by Factory.

This thread may be large but I need core team members to help me clearly minds


You should not use $objectManager directly because it takes control from clients of your code and leads to higher code coupling

We split all objects to two groups: injectables & non-injectables.

Injectables - all services, mostly stateless classes like FrontController or EventManager should be requested in object constructors.

Non-Injectables - all entities, mostly stateful objects like Product or Category should be created through Factories. And Factories should be requested in constructors.

You can read more here: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/depend-inj.html#dep-inj-mod-type-life-mgmt

| improve this answer | |
  • Sometime i got null object while use factory. It related to shared object create? – mrtuvn Feb 4 '16 at 16:20
  • What do you mean by null object? Is it null value? – Anton Kril Feb 4 '16 at 16:27
  • i request model factory from block by ->create('id') like this. Results get null. May be i am doing wrong somewhere – mrtuvn Feb 5 '16 at 4:40
  • I have a question. I have a model, how to get id of this model use Factory, I should get id in model or model resourceCollection. Magento 2 use getId and getById somewhere, it make me some confusing – mrtuvn Feb 24 '16 at 3:15
  • to create a model you use $modelFactory->create(); To load a Model directly from a Factory you can use $modelFactory->create()->load($id); To get the ID of a Model you use $model->getId(); The getById($id) is typical for Repositories which can also create you modelinstancens like $modelRepository->getById($id) – David Verholen Feb 24 '16 at 3:27

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.