Skip to content

Essential APIs - Configuration API

The configuration API is for storing and sharing system settings across environments. For local variables that shouldn't travel across environments (such as cron last run time), use the State API instead.

See the Configuration Management section for more details about managing configurations.

Reading from the config:

php
<?php
//Immutable Config (Read Only)
$config = \Drupal::config('system.performance');
$message = $config->get('message');

$page_cache = \Drupal::config('system.performance')->get('cache.page');
?>

Writing to the config:

php
<?php
//Mutable Config (Read / Write)
$config = \Drupal::service('config.factory')->getEditable('system.performance');

// Set a scalar value.
$config->set('cache.page.enabled', 1);

// Set an array of values.
$config->set('cache.page', ['enabled' => 1, 'max_age' => 5]);

// Save your data to the file system.
$config->save();

// Or 
 $config = \Drupal::configFactory()->getEditable('system.performance')
      ->set('cache.page', ['enabled' => 1, 'max_age' => 5])
      ->save();
?>

  1. hook_config_import_steps_alter()
  2. hook_config_schema_info_alter()

Questions

General

What is the purpose of the Configuration API in Drupal?

The configuration API is for storing and sharing system settings across environments

Which service is used to access configuration in Drupal? How do you access it?

config.factory; \Drupal::service('config.factory')

What are the two types of configuration objects?

Immutable Config (Read Only) and Mutable Config (Read / Write)

How do you access the configuration object?

There is two ways to access it:

php
// Immutable Config (Read Only).

// Procedural code:
$config = \Drupal::config('system.performance');

// With dependency injection:
// 'config.factory' service injected as $config_factory.
$config = $config_factory->get('system.performance');

To write to a configuration:

php
// Mutable Config (Read / Write).

// Procedural code:
$config = \Drupal::configFactory()->getEditable('system.performance');

// With dependency injection:
// 'config.factory' service injected as $config_factory.
$config = $config_factory->getEditable('system.performance');

Backend Developer (Advanced)

Which YAML file is used to define default configuration for a custom module?

my_module/config/install/*.yml

What is the purpose of a configuration schema file and where is the correct location for defining a configuration schema file?

To describe the structure of a configuration file for validation and translation; my_module/config/schema/my_module.schema.yml

How can you ignore specific configuration files from being synchronized?

By modifying settings.php and adding $config['config_exclude_files'][] = 'config_name';


Resources