I just saw that Magento is going to deprecate load and save functions which we use in loading and saving models. Can someone provide some insights on this? What alternate we will be having now to use?
1 Answer
So, first of all, you always should use Repository to load and save objects.
If there is a reason not to do this, everything is in phpDoc of load
and save
methods:
/**
* Save object data
*
* @return $this
* @throws \Exception
*
* @deprecated 100.1.0 because entities must not be responsible for their own persistence.
* Service contracts should persist entities. Use resource model "save" to implement
* service contract persistence operations.
*/
if you need to load or save object, you should:
- Inject in
__constructor
modelFactory - Inject in
__constructor
resourceModel
For load
$id = 1;
$modelEmptyObject = $this->modelFactory->create();
$this->resourceModel->load($modelEmptyObject, $id);
For save
$modelEmptyObject = $this->modelFactory->create();
$modelEmptyObject->setA('asd');
$modelEmptyObject->setB('qwe');
$this->resourceModel->save($modelEmptyObject);
And remember that both of them could throw exceptions, load can throw NoSuchEntityException
and save can throw AlreadyExistsException
And just FYI, they are deprecated since 2.1.0
version.