Magento – Implementing custom session class

magento2session

In Magento 2 we have different classes to access session, depending on context we want to access it, for example \Magento\Customer\Model\Session or \Magento\Checkout\Model\Session. Recently I was wondering if in case of some bigger custom modules, when there is a need to use some session variables and so on it's good idea to implement custom session class to access php session.
If there a sense to do it, has anyone tried to do it, and can share some code or point some important issues while doing it.

Best Answer

Add following config into global di.xml [SR/StackExchange/etc/di.xml]

<virtualType name="SR\StackExchange\Model\Session\Storage" type="Magento\Framework\Session\Storage">
    <arguments>
        <argument name="namespace" xsi:type="string">stackexchange</argument>
    </arguments>
</virtualType>
<type name="SR\StackExchange\Model\Session">
    <arguments>
        <argument name="storage" xsi:type="object">SR\StackExchange\Model\Session\Storage</argument>
    </arguments>
</type>

SR/StackExchange/Model/Session.php

namespace SR\StackExchange\Model;

class Session extends \Magento\Framework\Session\SessionManager
{

}
Related Topic