Skip to content

Latest commit

 

History

History
38 lines (28 loc) · 1.37 KB

4.4-essential-apis-state.md

File metadata and controls

38 lines (28 loc) · 1.37 KB

State API

From State API Overview:

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');
?>

Additional Resources