public function getShipAddress($customerId){
$customer = $this->_customerFactory->create()->load($customerId); //insert customer id
//shipping
$shippingAddressId = $customer->getDefaultShipping();
$shippingAddress = $this->_addressFactory->create()->load($shippingAddressId);
return $shippingAddress;
}
2 Answers
Please use RepositoryInterface
to load instead of model load()
function
public function __construct(
...
\Magento\Customer\Api\AddressRepositoryInterface $addressRepository,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
...
) {
$this->addressRepository = $addressRepository;
$this->customerRepository = $customerRepository;
}
public function getShipCustomer($customerId)
{
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $this->customerRepository->getById($customerId);
$shippingAddressId = $customer->getDefaultShipping();
/** @var \Magento\Customer\Api\Data\AddressInterface $shippingAddress */
$shippingAddress = $this->addressRepository->getById($shippingAddressId);
return $shippingAddress;
}
Models
are Data Interface are used to only hold the data in objects, i.e toset
andget
data for a row.ResourceModels
are a mechanism which is responsible for the persistence of such data, i.e execute the SQL query to actuallysave
orload
data into theModel
object.
The correct way to load
and save
should be by creating a repository or loading from a resource as follows:
namespace MyVendor\MyModule\Model;
class QueueRepository
{
/** @var \MyVendor\MyModule\Model\ResourceModel\Queue */
public $resource;
/** @var \MyVendor\MyModule\Model\QueueFactory */
public $modelFactory;
public function __construct(
\MyVendor\MyModule\Model\ResourceModel\Queue $resource,
\MyVendor\MyModule\Model\QueueFactory $modelFactory
) {
$this->resource = $resource;
$this->modelFactory = $modelFactory;
}
/**
* Save
* @param \MyVendor\MyModule\Api\Data\QueueInterface $queue
* @return $queue
* @throws \Exception
*/
public function save(\MyVendor\Integrator\Api\Data\QueueInterface $queue)
{
$this->resource->save($queue);
return $queue;
}
/**
* Save
* @param \MyVendor\MyModule\Api\Data\QueueInterface $queue
* @param int $id
* @return $queue
* @throws \Exception
*/
public function load(\MyVendor\MyModule\Api\Data\QueueInterface $queue, $id)
{
$this->resource->load($queue, $id);
return $queue;
}
public function getById($id)
{
$queue = $this->modelFactory->create();
$this->resource->load($queue, $id);
return $queue;
}
}
Here, \MyVendor\MyModule\Api\Data\QueueInterface
is implimented by Queue
Model.
So, behind the scenes, we are actually creating an Model
object then loading
it by the ResourceModel
object.
This is the correct way to load or save.
$queue = $this->modelFactory->create();
$this->resource->load($queue, $id);
return $queue;