| name | drupal-state |
| description | Drupal State API — storing and retrieving runtime state that persists across requests but is not configuration. |
Drupal State API
State is for runtime data that should persist across requests but is NOT configuration. Use Config for user-managed settings. Use State for internal operational data (last cron run, migration status, etc.).
Basic Usage
use Drupal\Core\State\StateInterface;
public function __construct(
private readonly StateInterface $state,
) {}
$value = $this->state->get('my_module.last_run');
$value = $this->state->get('my_module.last_run', $default_value);
$this->state->set('my_module.last_run', \Drupal::time()->getRequestTime());
$this->state->delete('my_module.last_run');
$values = $this->state->getMultiple(['key1', 'key2']);
$this->state->setMultiple([
'my_module.status' => 'active',
'my_module.count' => 42,
]);
$this->state->deleteMultiple(['key1', 'key2']);
Naming Convention
Use a namespaced key: module_name.key_name
$this->state->get('my_module.last_import_time');
$this->state->get('my_module.processed_count');
$this->state->get('last_import');
State vs Config vs Cache
| Storage | Use for | Exportable |
|---|
| State | Runtime operational data (last run times, counters, flags) | No |
| Config | User-managed settings, site configuration | Yes (via cex/cim) |
| Cache | Expensive computed data, invalidated on change | No (temporary) |
| UserData | Per-user preferences/data | No |
Common Use Cases
$this->state->set('my_module.cron_last', \Drupal::time()->getRequestTime());
$isEnabled = $this->state->get('my_module.feature_enabled', FALSE);
$this->state->set('my_module.migration_offset', $offset);
$this->state->set('my_module.api_token_expires', $expires);
Drush State Commands
drush state:get my_module.last_run
drush state:set my_module.feature_enabled 1
drush state:del my_module.last_run
Service ID
state