
This article was written in 2020 for Drupal 8. Some APIs and examples may have changed since: check the documentation for your Drupal version.
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:
- A new content type and the necessary fields are created during the development of a new feature.
- Once the feature is implemented in the development environment, configurations can be exported from the database via the command
drush config-exportin.ymlfile format, which are then versioned using git and later imported to another environment viadrush config-import.
Using the Configuration Management API
- 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');
State API
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.
Interacting with State API
-
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);
Conclusion
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 | ❌ | ✅ |
