Alternative to Magento 2 Deprecated save and load methods in Abstract Model
Many of you might have been experienced that use of load() and save() method of your Module model file has been deprecated. You might have faced that many times while loading product, quote or order. If you are using PhpStorm it’s showing a deprecated method like this screenshot.
In this code snippet, we will see an alternative to Magento 2 deprecated save and load methods in Abstract Model.
Alternative to Magento 2 Deprecated Load Method
ResourceModel’s load method is an alternative to AbstractModel’s load method. You can use like below code snippet.
class TestRepository implements TestRepositoryInterface { private $customerResource; private $customerFactory; public function __construct( \Magento\Customer\Model\ResourceModel\Customer $customerResource, \Magento\Customer\Model\CustomerFactory $customerFactory ){ $this->customerResource = $customerResource; $this->customerFactory = $customerFactory; } public funtion getCustomer($id) { $customerModel = $this->customerFactory->create(); $this->customerResource->load($customerModel, $id); $customerModel->getEmail(); } }
To load customer we have to use the ResourceModel’s load method of customer module. This method accepts two parameters. The First parameter is Model Object and second parameter is the id you want to load.
Alternative to Magento 2 Deprecated Save Method
ResourceModel’s save method is an alternative to AbstractModel’s save method. You can use like below code snippet.
class TestRepository implements TestRepositoryInterface { protected $taskFactory; protected $resource; public function __construct( \Codextblog\Task\Model\ResourceModel\Task $resource, \Codextblog\Task\Model\TaskFactory $taskFactory ){ $this->resource = $resource; $this->taskFactory = $taskFactory; } public funtion save($taskData) { $taskModel = $this->taskFactory->create()->setData($taskData); $this->resource->save($taskModel); } }
To save the task model data we have to use ResourceModel’s save method of task module. This method accepts only one parameter that is the model object.
Hope this code snippet helps you.To receive update about this type of code snippet, please like us on Facebook and follow us on Twitter.
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me