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

1

5

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

Yokefellow answered 18/3, 2018 at 15:19 Comment(0)
G
7

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

Guillermoguilloche answered 18/3, 2018 at 18:20 Comment(2)
Thanks a lot. It helps me.Yokefellow
@WowRenga No problem! I see you're fairly new to SO. If you feel this answer solved your problem, please mark it as 'accepted' by clicking the green check mark. This helps keep the focus on questions which still do not have answers.Guillermoguilloche

© 2022 - 2024 — McMap. All rights reserved.