Now, I want to briefly talk about another user-specific storage option, provided by the User module, called UserData.
The purpose of the UserData API is to allow the storage of certain pieces of information related to a particular user. Its concept is similar to the State API in that the type of information stored is not configuration that should be exported. In other words, it is specific to the current environment (but belonging to a given user rather than a system or subsystem).
Users are content entities, who can have fields of various data types. These fields are typically used for structured information pertaining to the user, for example, a first and a last name. However, if you need to store something more irregular, such as user preferences or flag that a given user has done something, the UserData is a good place to do that. This is because the information is either not something structured or is not meant for the users themselves to manage. So, let's see how this works.
The UserData API is made up of two things—the UserDataInterface, which contains the methods we can use to interact with it (plus developer documentation), and the UserData service, which implements it and can be used by the client code (us):
/** @var \Drupal\user\UsedDataInterface $userData */
$userData = \Drupal::service('user.data');
We are now ready to use the three methods on the interface:
- get()
- set()
- delete()
The first three arguments of all these methods are the same:
- $module: to store data in a namespace specific to our module name, thereby preventing collisions
- $uid: to tie data to a given user—it doesn't have to be the current user
- $name: the name of the entry being stored
Naturally, the set() method also has the $value argument, which is the data being stored, and this can be any scalar value or serializable object.
Together, all these arguments make for a very flexible storage system, a much improved one compared to the Drupal 7 option. We can essentially, for one module, store multiple entries for a given user and it doesn't stop there. Since that is possible, many of these parameters are optional. For example, we can get all the entries for a given module at once or all the entries for a given module and user combination at once. The same goes for deleting them. But where does all this data go?
The user module defines the users_data database table whose columns pretty much map to the arguments of these methods. The extra serialized column is there to indicate whether the stored data is serialized. Also, in this table, multiple records for a given user can coexist.
That is all there is to say about the UserData API. Use it wisely. Now it's time to turn to the configuration API, one of the biggest subsystems in Drupal 8.