Magento2 how to load customer model object

Magento2 have changed model classes a lot.

For example we need to use $customer object inside Review model class. Then step by step instruction will look this:

Add code to file: Model/Review.php


/**
* Review status collection factory
*
* @var \Magento\Review\Model\ResourceModel\Review\Status\CollectionFactory
* @param \Magento\Review\Model\Review\Summary $reviewSummary
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\UrlInterface $urlModel
+ * @param \Magento\Customer\Api\CustomerRepositoryInterface\Proxy $customerRepository
* @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
* @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
* @param array $data

\Magento\Review\Model\Review\Summary $reviewSummary,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\UrlInterface $urlModel,
+ \Magento\Customer\Api\CustomerRepositoryInterface\Proxy $customerRepository,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
+ $this->customerRepository = $customerRepository;
$this->productCollectionFactory = $productFactory;
$this->_statusFactory = $statusFactory;
$this->_summaryFactory = $summaryFactory;

return $this->_urlModel->getUrl('review/product/view', ['id' => $this->getReviewId()]);
}

Here is new parameters to load customer object:

* @param \Magento\Customer\Api\CustomerRepositoryInterface\Proxy $customerRepository


\Magento\Customer\Api\CustomerRepositoryInterface\Proxy $customerRepository,


$this->customerRepository = $customerRepository;

Then create new method to load customer object

+ public function getCustomer()
+ {
+ $customer = $this->customerRepository->getById($this->getCustomerId());
+ return $customer;
+ }

And last step is to update module config xml
etc/di.xml



Magento\Framework\Url
+ Magento\Customer\Api\CustomerRepositoryInterface\Proxy


Leave a Reply

Your email address will not be published. Required fields are marked *