Renga
Renga

Reputation: 221

In Magento 2 what is the factory pattern and used for?

In Magento 2 what is the factory pattern and used for ? I'm new in magento so can you please explain me in detail.

Upvotes: 5

Views: 7613

Answers (1)

AJK
AJK

Reputation: 435

Factory Definition :

Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity. They create a layer of abstraction between the ObjectManager and business code.

Repository Definition :

A repository object is responsible for reading and writing your object information to an object store

Use Repositories for full loading $model->load() is not part of the service contract. I had a question on that particular topic, you might find the answers useful: Is there ever a reason to prefer $model->load() over service contracts?

Use Factories to create new entities Repositories do not come with methods to create a new entity, so in that case you will need a factory. But use the factory for the interface, such as Magento\Catalog\Api\Data\ProductInterfaceFactory - it will create the right implementation based on DI configuration.

Then use the repository->save() method to save it.

https://magento.stackexchange.com/questions/158081/when-should-we-use-a-repository-and-factory-in-magento-2

More here in the dev docs http://devdocs.magento.com/guides/v2.0/extension-dev-guide/factories.html

Upvotes: 7

Related Questions