1

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 1

3

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:

  1. Inject in __constructor modelFactory
  2. 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.

1
  • superb explaination.Thanks :) Commented May 16, 2020 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.