TransWikia.com

Load resource models without using deprecated getResource

Magento Asked by Dominic Pixie on December 9, 2021

I’m using MagentoNewsletterModelResourceModelSubscriber::loadByCustomerData

Code is like this

 /** @var MagentoCustomerApiDataCustomerInterface $customer */

 [...]

 $subscriber = $this->subscriberFactory->create();

 $array = $subscriber->getResource()
     ->loadByCustomerData($customer);
 [...]

I spotted that getResource is @deprecated because resource models should be used directly which makes sense.

What would be the correct way to do this without using deprecated code?

One Answer

The correct way is that calling the Resouce model MagentoNewsletterModelResourceModelSubscriber directly at your model class or service contact class instead of call Model class getResource().

As Magento following Service concept design pattern https://devdocs.magento.com/guides/v2.4/extension-dev-guide/service-contracts/service-contracts.html, So model class used as Data provide a class that getResource() is deprecated at magento2.

Like MagentoCmsApiDataBlockInterface is rewrite by MagentoCmsModelBlock.

/**
* @var $subscriber MagentoNewsletterModelResourceModelSubscriber
*/
$subscriberResource = $this->subscriberResource;

$array = $subscriberResource->loadByCustomerData($customer);

Check the How to implement service contract for a custom module in Magento 2? about service contract.

Example:

<?php
namespace {NameSpace};

// Alias of Class
use MagentoNewsletterModelResourceModelSubscriber as SubscriberResourceModel;

class {Classname}{
    
    private $subscriberResource;
    public function __construct(
        SubscriberResourceModel $subscriberResource,
        .....
    ) {
        .....
        $this->subscriberResource = $subscriberResource;
        ....
    }   
}

Answered by Amit Bera on December 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP