Drupal 8: Tempstore

Drupal 8 has a powerful mechanism to temporarily store data. Tempstore resembles storing data in session, and it also persists between the page reloads. There are two major types of storage that I ended up using: private tempstore and shared tempstore.

Private Tempstore

Private temporary storage is used to temporarily store user-specific information, like intermediary multistep form results or persistent choice made somewhere on the site (like cookies agreement). Private temporary storage has built-in checks to make sure the information is selectively used for the user. Even if user is not logged in, his session identification will be used to identify him and access his storage data, if session gets started in code.

$tempstore = \Drupal::service('user.private_tempstore')->get('my_module_name');
$tempstore->set('key_name', $key_value);
$value = $tempstore->get('key_name');
$tempstore->delete('key_name');

Shared Tempstore

Shared tempstore is also used to temporarily store user-specific information, but it is accessible from outside. This is used, for example, in cases, when the data is not private, and it is desirable to check the status of another owner (for example, the views uses this kind of storage to make sure that two users don't work on the same view at once.

$tempstore = \Drupal::service('tempstore.shared')->get('my_module_name');
$tempstore->set('key_name', $key_value);
$value = $tempstore->get('key_name');
$tempstore->delete('key_name');