The need to share configurations across environments in a Drupal project is a recurring requirement. The Features module used to allow developers to share various configurations between development and production environments in Drupal 7. Features was one of the most widely used and essential modules due to its flexibility and effectiveness. This drove the community to introduce a Configuration and Synchronization API directly into Drupal 8 Core.
Here is a simple Configuration API usage scenario:
drush config-export in .yml file format, which are then versioned using git and later imported to another environment via drush config-import.Get a value from configuration:
$slogan = \Drupal::config('system.site')->get('slogan');Save a value in configuration:
$slogan = \Drupal::config('system.site')->set('slogan','value');The State API allows storing environment-specific information. In other words, the goal is to keep certain information that is specific to each environment — the simplest example being recording the last time Cron ran. This information depends on each environment, so it must be stored in State. The concept of a State API exists in most frameworks under different names ("envs-variables", "sys-vars"...) but the idea is the same.
Get a value:
$value = \Drupal::state()->get('key');Get multiple key/value pairs:
$values = \Drupal::state()->getMultiple($keys);Save a value:
\Drupal::state()->set('key','value');Save multiple values:
\Drupal::state()->setMultiple($keyvalues);Delete a value:
\Drupal::state()->delete('key');Delete multiple values:
\Drupal::state()->deleteMultiple($keys);Both APIs allow storing data. The table below summarizes the key differences between the two.
| Configuration API | State API | |
|---|---|---|
| Data can be shared across environments | ✅ | ❌ |
| Data can be modified by users | ✅ | ❌ |
| The API is used to store system state information | ❌ | ✅ |