20

What is the best way to load Customer by Id? using customer interface or customer factory or another way ?
In most of solutions I found, it is done by directly using objectManager (which should be never be used).

Vishwas Bhatnagar
  • 4,679
  • 3
  • 38
  • 60

1 Answers1

38

It's always a better practice to use service contracts.

In your case I would use \Magento\Customer\Api\CustomerRepositoryInterface :

protected $_customerRepositoryInterface;
public function __construct(
    ....
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    ....
) {
    ....
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
}

Then in your code you can call:

$customerId = 1;
$customer = $this->_customerRepositoryInterface->getById($customerId);
Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352
  • 4
    not working ... i have keep it in helper/data.php and call this method in phtml file but not working. – Sarfaraj Sipai Jun 21 '18 at 09:05
  • why its not working in helper class or Model/class? – Ajwad Syed Jun 29 '20 at 15:30
  • 1
    It does work, but you can't retrieve information like firstname with $customer->getData('firstname'); it only works with $customer->getFirstname(); which is confusing. You can find all methods here: vendor\magento\module-customer\Api\Data\CustomerInterface.php – Black Apr 26 '21 at 10:50