2

In Magento, we could use as $this->_getSession()->clear();

However, in magento 2 if we use the same thing it throws exception as

Invalid method Magento\Backend\Model\Session\Interceptor::clear

Is there any way to do this in Magento 2?

I tried to search about this but could not find anything relevant.

Please, can anyone help?

4

I believe the method you are looking for in Magento 2 is destroy().

Take a look at the following class Magento\Backend\Model\Session it extends \Magento\Framework\Session\SessionManager which has two methods that you would find helpful.

  • clearStorage() which clears all the stored data from the session and still keeps the session active
  • destroy() which ends a session

The destroy() method allows you to carry out a combination of 2 actions, Clear Storage and or end session, whereas the clearStorage() method only clears the storage

| improve this answer | |
3

For frontend,

protected $session;

public function __construct(
    \Magento\Framework\Session\SessionManagerInterface $session
) {
    $this->session = $session;
}

//Unset all session data front

$this->session->clearStorage();

/* Destroy/end session front */
/* if you want to destroy specific session pass array value 
* otherwise null
*/

$this->session->destroy(array $options = null);

For Backend

protected $adminSession;

public function __construct(
    \Magento\Backend\Model\Auth\Session $adminSession
) {
    $this->adminSession = $adminSession;
}

//Unset all admin session data

$this->adminSession->clearStorage();

//Destroy/end admin session
/* if you want to destroy specific session pass array value 
* otherwise null
*/

$this->adminSession->destroy(array $options = null);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.