Configuration is a place to store information that you want to synchronize from development to production. This information is often created during site building and is not typically generated by regular users during normal site operation.
You should use the State API, not Configuration API, for storing local variables that shouldn't travel between instances.
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 deploy to deploy it between environments.
- You can reset a system, losing all state. Its configuration remains.
A good example of State API use is storing the timestamp of the last cron operation run.
State API
Writing Values
For entry, we should use a pair: a key and a value.
Drupal::state()->set("key","value");
For multiple entries we use the following code:
// $values - array with the couple of key and value.
$values = [
'key1' => 'value1',
'key2' => 'value2'
];
Drupal::state()->setMultiple($values);
State API: Getting Data
Getting one value with a key.
$val = Drupal::state()->get("key");
Getting several values:
$keys = [
'key',
'key2'
];
$pairs = Drupal::state()->getMultiple($keys).// $values - array with the couple of key and value.
$values = [
'key1' => 'value1',
'key2' => 'value2'
];
Drupal::state()->setMultiple($values);
State API: Deleting Data
Deletig is accessible only with one value:
Drupal::state()->delete("key");
When you use Configuration API, setup data will be saved. If you export the website configuration, you’ll find name.settings.yml file with the following content key value.
Configuration API
Creating the Configuration Object
$config = Drupal::config(‘name.settings');
Configuration API: Writting values.
$config->set('key','value');
$config->save();
Configuration API: ????????? ??????.
$config->get('key'); // value.
Configuration API: Deleting data.
$config->delete('key');
$config->save();
Now if you export the website configuration, you’ll find name.settings.yml file with the following content key value.