Magento – How to set and get customer session data in magento 2

customer-sessionmagento2

I am struggling with magento 2 session. I have created below controller file as a sample code.

<?php
namespace vendor_name\module_name\Controller\SetGetSession;

use Magento\Framework\App\Action\Action;

class SetGetSession extends Action
{
    protected $customerSession;

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

    public function execute()
    {

    }
}

Can anyone please help me with how to assign data and retrieve it from session variable?

Thank you.

Best Answer

You can Set and get Customer session by using Magento\Customer\Model\Session

protected $customerSession;

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

$this->customerSession->setMyValue('test');
$this->customerSession->getMyValue();

Or by object manager.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
$customerSession->setMyValue('test');
$customerSession->getMyValue();
  1. Setting an information to the customer session:
$om = \Magento\Framework\App\ObjectManager::getInstance(); $session =
$om->get('Magento\Customer\Model\Session');  
$session->setTestKey('test value');
  1. Getting an information from the customer session:
$om = \Magento\Framework\App\ObjectManager::getInstance();  $session =
$om->get('Magento\Customer\Model\Session');
echo $session->getTestKey();

Session will extends core class Magento\Framework\Session\SessionManager to handle the session.

Hope this answer will help you.