Skip to main content

How to store session data in Drupal 8

calendar_todayJune 23, 2017 Jeevitha

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.
 

Subscribe to our blogs

The subscriber's email address.

Related Posts

Drupal Performance
13 ways to maximize Drupal performance
Site speed is crucial when you run a site. If a site takes too much time to load, visitors will get frustrated and…
Form API in Drupal 8
How to create custom forms in Drupal 8
Drupal 8 Form API is similar to Drupal 7 form API. The forms are still represented with nested array structure as…
Drupal Security
6 Drupal modules to better protect your website from…
Drupal is powered by best-of-the-breed technologies which makes Drupal highly customizable and scalable. Drupal is free…

start with anubavam today

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

Request Quote