Private TempStore

The following is a simple example of what we just talked about:

/** @var DrupalCoreTempStorePrivateTempStoreFactory $factory */
$factory = Drupal::service('user.private_tempstore');
$store = $factory->get('my_module.my_collection');
$store->set('my_key', 'my_value');
$value = $store->get('my_key');

First, we get the PrivateTempStoreFactory service and ask it for the store identified by a collection name we choose. It's always a good idea to prefix it with your module name to avoid collisions. If another module names their own collection my_collection, it's not going to be pretty (even if the store is private).

Next, we use very simple setters and getters to set values similar to how we did with the State API.

If you run this code as user 1 (the main admin user), you'll note a new entry in the key_value_expire database table. The collection will be user.private_tempstore.my_module.my_collection, while the name will be 1:my_key. This is the core principle of the private tempstore: each entry name is prefixed with the ID of the user who is logged in when the entry was created. Had you been an anonymous user, it would have been something like this: 4W2kLm0ovYlBneHMKPBUPdEM8GEpjQcU3_-B3X6nLh0:my_key, where that long string is the session ID of the user.

The entry value will be a bit more complex than with the State API. This time it will always be a serialized stdClass object, which contains the actual value we set (which itself can be any scalar value or object that can be properly serialized), the owner (the user or session ID), and the last updated timestamp.

Lastly, we have the expire column, which, by default, will be one week from the moment the entry was created. This is a "global" timeframe set as a parameter in the user.services.yml definition file and can be altered in your own services definition file if you want. However, it is still global.

We can also delete entries like so:

$store->delete('my_key'); 

And we can also read the information I mentioned before about the entry (the last update date, owner):

$metadata = $store->getMetadata('my_key'); 

This returns the stdClass object that wraps the entry value, but without the actual value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset