Skip to main content
Jeevitha

How to store session data in Drupal 8


store session data

In Drupal 8, there is a need to store information associated with a user's session. There are two services for temporarily storing user-specific and non-user-specific data in key/value format, namely, use user.private_tempstore and user.shared_tempstore.

TempStore

A tempstore is for data that needs to be persisted between requests without being saved back to the canonical storage (such as an entity or configuration object).  

Two methods can be effectively used for  private_tempstore - Use "\Drupal::service()" and Dependency Injection.

Use "\Drupal::service()"

To set Temporary Data

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

To read Temporary Data

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->get('my_variable_name', $some_data);

PrivateTempStore

A PrivateTempStore can be used to make temporary, non-cache data available across requests. The data for the PrivateTempStore is stored in one key/value collection. PrivateTempStore data expires automatically after a given timeframe.

Dependency Injection

  • To use this service need to invoke the following “use” statement

          use Drupal\user\PrivateTempStoreFactory;

          use Symfony\Component\DependencyInjection\ContainerInterface;

  • Temporary store - that is private to the current user.

Storing session data vs storing temporary data

Which is efficient, storing data using session variable or use data for a limited term. Let's see which approach is preferable: 

  • Both are used for same purpose.
  • But Drupal 8 services provides needed abstraction and structure for interacting with a global construct. It's part of an overall architecture that allows Drupal developers to build and extend complex applications.
  • Use session manager for anonymous user to store the data.

Stay connected with the latest news on web strategy, design, and Drupal 8 development.
 

Tags : Drupal Modules
share :
Comments

Leave Your Comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
 

start with anubavam today

You have an idea we have engineers to convert your ideas into reality

Request Quote