4

Which class I should inject to get the current customer? What are their differences?

  1. \Magento\Customer\Helper\Session\CurrentCustomer
  2. \Magento\Customer\Model\Session
Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352
TFS
  • 4,319
  • 17
  • 46
  • 74

1 Answers1

6

Well, you can use either of them.

Basically \Magento\Customer\Helper\Session\CurrentCustomer uses \Magento\Customer\Model\Session.

The benefit of using the helper class is that it provides extra helper methods to get the current customer data such as:

  • getCustomer : to load the current customer
  • getCustomerId : to get the current customer id

The benefit of using the model class is that you modify the customer data with:

  • setCustomerData
  • setCustomer
  • setCustomerId
  • setCustomerGroupId
  • setCustomerAsLoggedIn

Also you can do extra stuff that the helper won't let you do:

  • check if the customer is logged in: isLoggedIn()
  • login with login()
  • logout with logout()

So I guess it depends on your needs:

  • if you only need to get customer data you can use \Magento\Customer\Helper\Session\CurrentCustomer
  • if you need to modify the current customer or interact with it, I suggest you use \Magento\Customer\Model\Session
Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352
  • Thanks for help and nice your answer. How to get current customer in magento 2? – Payal Patel Sep 01 '16 at 12:32
  • 2
    @PayalPatel here's an answer for you: http://magento.stackexchange.com/questions/92818/get-customer-in-product-view NB: please try to avoid using the object manager directly and inject the class in your constructor directly instead – Raphael at Digital Pianism Sep 01 '16 at 12:34