38
22
I have gone through a couple of tutorials in Magento 2, and this confuses me a little. I can see there are basically two ways by which we can read/write business entities:
Retrieve Data
Using A Factory Approach
$object = $this->myFactory->create();
$object->load($myId);
Using A Repository Approach
$repo = $this->myRepository();
$object = $repo->getById($myId);
Save Data
Using A Factory Approach
$object = $this->myFactory->create();
$object->load($myId);
$object->setData('something', 'somethingDifferent')->save();
Using A Repository Approach
$repo = $this->myRepository();
$object = $repo->getById($myId);
$object->setData('something', 'somethingDifferent');
$repo->save($object);
I can also see that, both a repository and a factory class can be injected using dependency injection. This is confusing at least for me.
When should we use a repository approach and a factory approach? What is the best practice we need to follow?
1Could you give a code example about use Factories to create new entities, the explanation miss some details and hard to understand. Thank you very much. – Key Shang – 2017-11-14T09:01:32.560
@Key does this help? http://devdocs.magento.com/guides/v2.2/extension-dev-guide/factories.html
– Fabian Schmengler – 2017-11-14T09:21:54.697Thanks. but the
use the factory for the interface, such as Magento\Catalog\Api\Data\ProductInterfaceFactory - it will create the right implementation based on DI configuration.
is the point which I can not understand, the dev guides doesn't introduce the InterfaceFactory , how to userepository->save()
method to save new entities? I can just only use factory to save new entities, not repository. – Key Shang – 2017-11-14T10:43:59.603