State API overview

Last updated on
20 July 2017

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 …

There is a list of common keys which might be used on the site:

$common_keys = array(
  'comment.maintain_entity_statistics',
  'comment.node_comment_statistics_scale',
  'drupal_css_cache_files',
  'install_task',
  'install_time',
  'node.min_max_update_time',
  'node.type.locked',
  'router.path_roots',
  'routing.menu_masks.router',
  'routing.non_admin_routes',
  'system.cron_key',
  'system.cron_last',
  'system.css_js_query_string',
  'system.js_cache_files',
  'system.maintenance_mode',
  'system.module.files',
  'system.private_key',
  'system.theme.data',
  'system.theme.files',
  'system.theme_engine.files',
  'twig_extension_hash_prefix',
  'views.view_route_names',
);

A good example of state is the last time cron was run ('system.cron_last'). 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.

Typical usage:

  • Get a value:
    $val = \Drupal::state()->get('key');
     
  • Get multiple key/value pairs:
    $pairs = \Drupal::state()->getMultiple($keys);
     
  • Set a value:
    \Drupal::state()->set('key','value');
     
  • Set multiple values:
    \Drupal::state()->setMultiple($keyvalues);
     
  • Delete a value:
    \Drupal::state()->delete('key');

Data which needs to be edited by humans or needs to be shared between environments should use \Drupal::config() instead. See the Configuration API info.

Documentation for class \Drupal\Core\State\State, Drupal's default StateInterface implementation.

General State API documentation.

Tags