6

In Magento 1 my code is

$customer = Mage::getSingleton('customer/session')->getCustomer();

How I set this code in Magento 2

7
Magento\Customer\Model\Session

is used in magento 2 to get object of Customer Session.

You can define in __construct() of php file,

public function __construct(
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->_customerSession = $customerSession;
    }

Now you can get the info using:

$customer = $this->_customerSession->getCustomer();
3
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$currentCustomer = $objectManager->get('Magento\Customer\Model\Session')->getCustomer();

Note: I am against of direct loading object with $objectManager, for better impact you can inject it in your constructor. I have just given example how you can achieve it. `

Better way


protected $_customerSession;

public function __construct(
\Magento\Customer\Model\Session $_customerSession 
) {
    $this->_customerSession=$_customerSession
}

Now you can easily get customer by simply

$this->_customerSession->getCustomer();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.