PrivateTempStore

The following is a simple example of what we talked about in the preceding section:

/** @var PrivateTempStoreFactory $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 ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.