Magento2 – Difference Between Factory vs ObjectManager While Instantiating Object

factorymagento2

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

Best Answer

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

Related Topic