'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.
Solution 1:[1]
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.
More here in the dev docs http://devdocs.magento.com/guides/v2.0/extension-dev-guide/factories.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SagarPPanchal |
