Magento 2 get and set session values
In my last post I showed you how to get session objects, now it is time to get and set session values. For this we programmatically set some values to session objects and get it again. Setting and getting values from and to session objects is really easy and helpful.
Magento 2 get and set session values
A session is a temporary object that is created on server for each Magento shop user to store some values (for example items in cart). Magento 2 knows different session objects as I showed you in my last article. If you want to store data that you need to pass from one page load to another for the same user, than you need to store it into a session.
Example
The easiest way to explain how to store information into a session object is a simple example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class MyTestSession { protected $session; public function __construct( \Magento\Framework\Session\SessionManagerInterface $session, ... ){ $this->session = $session; ... } public function setValue($value){ $this->session->start(); $this->session->setMessage($value); } public function getValue(){ $this->session->start(); return $this->session->getMessage(); } public function unSetValue(){ $this->session->start(); return $this->session->unsMessage(); } } |
This simple class uses a session object to store information. You can call setValue($value), getValue() and unSetValue() to work with this. This getter and setter methods set an attribute message with given value. You can call this attribute as you want. It is important, that you call start() before using a session. Otherwise you will get an error, if there is no session. start() will generate a new session object or does nothing.
You can use this simple class to store values on server side and use it on multiple pages.
Conclusion
In a simple example I showed you how to get and set session values for Magento 2 shops. Sessions are the easiest way to pass variables across different pages. A session will be destroyed after timeout passes.
Why do you need to use session variables for Magento 2?