Magento 2 get session
This time I show you how to get session programmatically from your Magento 2 shop. But before this can be done, we need to take a closer look on Magento 2 sessions .
Magento 2 get session
Magento 2 has many different session we can use to get and store information:
- \Magento\Backend\Model\Session
this is the session for your adminhtml and it is created if you log in into you Magento 2 backend. The source file is this one: vendor/magento/module-backend/Model/Session.php - \Magento\Catalog\Model\Session
frontend product catalog has also a session to store your filter settings: vendor/magento/module-catalog/Model/Session.php - \Magento\Checkout\Model\Session
checkout data is stored in this specific session object. The source file is this one: vendor/magento/module-checkout/Model/Session.php - \Magento\Customer\Model\Session
another important frontend session, which has information about frontend login. The source file is this one: vendor/magento/module-customer/Model/Session.php - \Magento\Newsletter\Model\Session
session for newsletters: vendor/magento/module-newsletter/Model/Session.php
Use a session (programmatically get a session)
For all session objects, it is important, that it was created before. Otherwise it is not possible to get one. It is not possible to get a backend session from a frontend block. If you want to use a session from your PHP class, you need to inject it. This is the same procedure for every session. This example shows only how to get customer session, but this code can be used for every other session too.
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Data extends AbstractHelper { private $customerSession; public function __construct( \Magento\Customer\Model\Session $customerSession, ... ) { $this->customerSession = $customerSession; ... } ... } |
This code shows how to create a new helper, that can use customer session to get and set information from and to customer session. For example, you can get information, if a customer is already logged in:
1 | $this->customerSession->isLoggedIn() |
Based on used session object, you can do different things. For detailed information about data that is stored in such a session, please check documentation or have a look in already mentioned core files.
Conclusion
It is easy to get session objects in Magento 2. It is important to use the right session. There are many different sessions and each offers you another set of data.
In some cases, this does not work and the Session will return false. than you can use the \Magento\Framework\App\Http\Context object, see https://magento.stackexchange.com/questions/206643/magento-2-2-2-customer-session-not-working-with-cache-enable