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.
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.
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);
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.
- To use this service need to invoke the following “use” statement
- 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.