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();
}
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();
}