Magento 2 get set unset session

Today we talk about how in Magento 2 get, set, and unset session. This tutorial include set session, get session and unset the session. Sometimes in customization and module development we need to get the session information , that how long a user remains on our site or we may need to unset the session given the certain amount of time . Following piece of code will let us to play with the global session variable to achieve our intended goals.

protected $coreSession;

public function __construct(
   
    \Magento\Framework\Session\SessionManagerInterface $coreSession
    ){

    $this->coreSession = $coreSession;
   
}

public function setSession(){
    $this->coreSession->start();
    $this->coreSession->setTest('The Core session');
}

public function getSession(){
    $this->coreSession->start();
    return $this->coreSession->getTest();
}

public function unSetSessione(){
    $this->coreSession->start();
    return $this->coreSession->unsTest();
}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply