Alternative to Magento 2 Deprecated save and load methods in Abstract Model

Alternative to Magento 2 Deprecated load method

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.

magento 2 load method

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)

All the comments are goes into moderation before approval. Please do not spam. Your email address will not be published. Required fields are marked *

Enjoy this post? Please support Us!

Like our social page for daily new updates….


Want to become
a Magento 2 Expert?

If Yes! Then Subscribe to our newsletter and get weekly article to you email id.
Subscribe Here
SUBSCRIBE NOW
close-link

To Avoid Spam Downloads, We Want Your Email

We will send you download link right
away. Please submit form below.
SEND ME DOWNLOAD LINK
Close