If you need a temporary buffer in Drupal to save data to, Drupal's tempstore service might come in handy. We used it for example in a webshop module, where users didn't have a saved address yet and also had to option to never save their address permanently (because of gdpr).
So, after some searching, the code is pretty straight forward. This example might save you some time to implement it
We implemented this in a custom Drupal webshop service, the functions are called in other code via dependency injection. So here is how to set and get your custom data with help of Drupal's tempstore:
(Be aware: the tempstore data wíll expire automatically)
/**
* Set data in Drupal's temp_store.
*
* @param array $vars
*/
public function setMyDataInTempStore(array $vars) {
// Get tempstore service.
$tempstore = \Drupal::service('tempstore.private');
// Get tempstore data we need.
$tempstore_data = $tempstore->get('my_custom_key');
$params = $tempstore_data->get('params');
// Fill vars.
$params['var_1'] = $vars['var_1'];
$params['var_2'] = $vars['var_2'];
// Save vars to tempstore.
$tempstore_data->set('params', $params);
}
/**
* Get data from Drupal's temp_store.
*
* @return array
*/
public function getMyDataInTempStore() {
// Get tempstore service.
$tempstore = \Drupal::service('tempstore.private');
// Get tempstore data we need.
$tempstore_data = $tempstore->get('my_custom_key');
$tempstore_params = $tempstore_data->get('params');
// Get vars.
$my_var_1 = $tempstore_params['var_1'];
$my_var_2 = $tempstore_params['var_2'];
// Return data in array.
return [
'var_1' => $my_var_1,
'var_2' => $my_var_2,
];
}