Essential APIs - State API
From State API over view on Drupal.org updated Apr 2024:
The State API provides a place for developers to store information about the system's state. State information differs from configuration in the following ways:
It is specific to an individual environment. You will never want to deploy it between environments. You can reset a system, losing all state. Its configuration remains. So, use State API to store transient information, that is okay to lose after a reset. Think: CSRF tokens
, tracking when something non-critical last happened … A good example of state is the last time cron was run. This is specific to an environment and has no use in deployment. The state API is a simple system to store this information, which previously would have been stored in the variables
system.
Usage:
<?php
// Retrieve the key value.
$key = \Drupal::state()->get('key');
// Retrieve multiple key values.
$keys = \Drupal::state()->getMultiple(['key1', 'key2', 'key3']);
// Set key value
\Drupal::state()->set('key','value');
// Set multiple key values
\Drupal::state()->setMultiple(['key1' => 'value1', 'key2' => 'value2']);
// Delete key
\Drupal::state()->delete('key');
// Deletes multiple items.
\Drupal::state()->deleteMultiple(['key1', 'key2', 'key3']);
?>
Questions
What is the primary purpose of the State API?
Answer: The State API is designed for the storage of information about the system's state, which is specific to an individual environment and not meant to be exported. It is also used for temporary storage of data that does not need to persist across deployments.
How can you read a state value using the State API?
Answer: You can read a state value using the get() method by providing the key, like this:
$single = \Drupal::state()->get('key');
$pairs = \Drupal::state()->getMultiple($keys);
What happens to state information when the database is reset?
Answer: All state information is lost when the database is reset, as it is stored in the database and not meant for deployment across environments.