Add a Custom Session
Would you like to add a custom session type in Magento 2? Are the default session types not the best practice to store the data you need? Let's see how you can create a custom session type and also how to set, get and unset data from the session.
Session are widely used in Magento 2 storing user's data for further user. Sessions are storing the data on server side.
As is well known in Magento 2 you can find the following session types:
- vendor/magento/module-catalog/Model/Session.php - Catalog Session Model
- vendor/magento/module-newsletter/Model/Session.php - Newsletter Session Model
- vendor/magento/module-persistent/Model/Session.php - Persistent Session Model
- vendor/magento/framework/Message/Session.php - Message Session Model
- vendor/magento/module-customer/Model/Session.php - Customer Session Model
- vendor/magento/module-backend/Model/Session.php - Backend Session Model
- vendor/magento/module-checkout/Model/Session.php - Checkout Session Model
To create now a custom session we will need to create session class which will extend to the SessionManager like below.What the SessionManager needs is the custom storage class to pass it as an argument and it will be the MageVision\Blog43\Model\Session\Storage.
The custom storage class can be a virtulType of the type Magento\Framework\Session\Storage passing as argument the namespace storage name, which is our example is the blog43. All the above will be implemented in the di.xml file like below.
Feel free to share this post and ask your questions in the comments below.
Till next time!