Magento 2 How To Set, Retrieve And Unset Session Variables

In Magento 2, we can set and unset session with following code snippet.

We can set/get/unset value in core session defined in following code snippet:

protected $coreSession;

public function __construct(
    \Magento\Framework\Session\SessionManagerInterface $coreSession
    ){
    $this->coreSession = $coreSession;
}

public function setValue(){
    $this->coreSession->start();
    $this->coreSession->setMessage('Test core session message text');
}

public function getValue(){
    $this->coreSession->start();
    return $this->coreSession->getMessage();
}

public function unSetValue(){
    $this->coreSession->start();
    return $this->coreSession->unsMessage();
}

Following are the different types of session available in Magento:

  • \Magento\Backend\Model\Session
  • \Magento\Catalog\Model\Session
  • \Magento\Checkout\Model\Session
  • \Magento\Customer\Model\Session
  • \Magento\Newsletter\Model\Session

Lets have a look how can we use these session. Now we will start calling catalog, customer, and checkout sessions through the following code snippet.

use Magento\Catalog\Model\Session as CatalogSession;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Checkout\Model\Session as CheckoutSession;
use \Magento\Framework\Session\SessionManagerInterface as CoreSession;

class ClassName {
    protected $coreSession;
    protected $catalogSession;
    protected $customerSession;
    protected $checkoutSession;

    public function __construct(
        CoreSession $coreSession,
        CatalogSession $catalogSession,
        CustomerSession $customerSession,
        CheckoutSession $checkoutSession
    ){
        $this->coreSession = $coreSession;
        $this->catalogSession = $catalogSession;
        $this->checkoutSession = $checkoutSession;
        $this->customerSession = $customerSession;
    }

    public function getCoreSession() 
    {
        return $this->coreSession;
    }

    public function getCatalogSession() 
    {
        return $this->catalogSession;
    }

    public function getCustomerSession() 
    {
        return $this->customerSession;
    }

    public function getCheckoutSession() 
    {
        return $this->checkoutSession;
    }
}

To set value in customer session:

$this->getCustomerSession()->setMyValue('OurCustomValue');

To get value in customer session:

$this->getCustomerSession()->getMyValue();

For unset session value in customer session:

$this->getCustomerSession()->unsMyValue();

This is all about sessions in Magento 2.

Hope this helps you guys!

Leave a Reply