Question

I'm using Magento\Newsletter\Model\ResourceModel\Subscriber::loadByCustomerData

Code is like this

 /** @var \Magento\Customer\Api\Data\CustomerInterface $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?

Was it helpful?

Solution

The correct way is that calling the Resouce model Magento\Newsletter\Model\ResourceModel\Subscriber 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 \Magento\Cms\Api\Data\BlockInterface is rewrite by \Magento\Cms\Model\Block.

/**
* @var $subscriber \Magento\Newsletter\Model\ResourceModel\Subscriber
*/
$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 Magento\Newsletter\Model\ResourceModel\Subscriber as SubscriberResourceModel;

class {Classname}{
    
    private $subscriberResource;
    public function __construct(
        SubscriberResourceModel $subscriberResource,
        .....
    ) {
        .....
        $this->subscriberResource = $subscriberResource;
        ....
    }   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top