📜 ⬆️ ⬇️

Configuration Management in Drupal 8, developer review

Drupal 8 brings with it many improvements and my favorite is configuration management . I will try to make a quick review on this topic.

Please remember that this review was written during the release of Drupal 8 beta 3. Something could change.

Types of information in Drupal 8


According to official documentation , we have four types of information:
  1. Content
  2. Session
  3. State
  4. Configuration

The good news is that almost everything except content is configuration: module settings, their states, blocks, block locations, content types, fields, display modes, and so on. All this information is processed during the import configurations. This makes the deployment process very simple.
')

Where configurations are stored


Let's take a look at the settings.php file on freshly installed Drupal 8.

 $config_directories['active'] = 'sites/default/files/config_XXXX/active'; $config_directories['staging'] = 'sites/default/files/config_XXXX/staging'; 

Here, XXXX is a long hash generated to protect your configuration from access from the web.

The active directory means storing your current configuration. I said “implied” because by default this directory is empty, and the current configuration is stored in a database. This is for security and performance reasons. However, you can change this behavior using the Configuration Tools module (config_tools). (Don't you remember that there is a module for everything ?;))

The staging directory is the place from where the configuration is imported / synchronized. This directory is also empty. If you do not use the option to import / export configurations.

Tip: Git


The sites/default/files directory is most often included in the .gitignore file and is ignored by Git, but you most likely want your configuration files to be managed by a version control system. The recommended way to place the configurations directory is outside the directory where Drupal is installed, so that it is not accessible to the web. And the easiest way is to move the configurations directory to the sites/default directory (but leave the hash in its name for security).

Built-in user interface


Out of the box, along with Drupal, is installed (in a standard profile) a Configuration Manager module (config) that provides a basic UI for managing configurations. It can be found on the admin/config/development/configuration path. The “Full Import / Export” tab is the most interesting here. The complete site configuration can be exported as a .tar.gz archive in the Export sub-tab. Then you can use this archive to import the configuration on another instance of the site.
image
When using this interface, the imported configuration file is not used immediately after loading, but is unpacked into the staging directory. After that, you need to start synchronization on the Synchronize tab, where you can also see the changes you have made.
image
That's all! Deployment is now available out of the box. No more extra tools needed!

If you do not want to use the UI, then Drush as always at your service.

 drush config-export #      staging drush config-import #     staging 

Unit of measurement configurations


Let's look at an example of an exported configuration.

 # file: system.site.yml
 uuid: c78fd9aa-b327-4514-9d00-bc72a1f40f27
 name: 'My cool site'
 mail: mailbox@example.com
 slogan: 'Drupal 8 rules!'
 page:
  403: ""
  404: ""
  front: node
 admin_compact_mode: false
 weight_select_max: 100
 langcode: en

Here, the configuration name is system.site . This is the unit of measurement for configuration. All configuration names should have at the beginning the name of the module or theme, in this case system .
The content of the file is very similar in structure to a regular PHP array. And when you work with configurations from code, you really will use arrays.

Tip: Best Practices


If your module / theme does not have a lot of settings, it is recommended to store them in one configuration with the name your_module_name.settings.

Working with configurations from a module or theme


Drupal 8 provides a very good API for working with configurations. Take a look at the code.

 $config = \Drupal::config('system.site'); // Instance of Drupal\Core\Config\Config $front_page = $config->get('page.front'); // 'node' $page_settings = $config->get('page'); // array( // '403' => '', // '404' => '', // 'front' => 'node', // ) $config->set('page.front', 'my-front-page'); $config->save(); 

Very simple, right? You can find most of the methods for working with configurations in the Drupal \ Core \ Config \ Config class. Also, other examples are available in the Simple Configuration API section of the developer documentation.

Default values


Remember how we specified default variable values ​​in Drupal 7?

 $value = variable_get('my_variable_name', 'my_default_value'); 

In Drupal 8, the default values ​​will no longer be scattered around the code. If you have a setting, set its default value during the module installation. There are two ways to do this:
  1. The simplest option is to place the YAML files in the config/install directory of your module.
  2. For cases where the default value must be calculated dynamically when the module is installed, use hook_install() .

You can find examples in the Comment module: in contact.form.feedback.yml , the value of recipients set to an empty array. Then, in contact_install() , the actual value is set.

Export configuration to module


There is one interesting point about the config/install directory.

In Drupal 7, we can export various functionality to the code of our modules. A common example: view for the administrative interface of the module. To do this, we need a basic knowledge of the Views API, some hooks, and some copy-and-paste. The Features module can also help us with this.

With Drupal 8, everything becomes much easier. Example for view:
  1. create view
  2. export site configuration
  3. find the YAML file of your view in the exported configuration (sample name: views.view.my_cool_view.yml )
  4. put this file in your module's config/install directory

Voila! Your view will be imported automatically when the module is installed.

Override configurations


One of the best features of Drupal is that we can change (replace) everything without touching the kernel and third-party modules. Configurations are no exception.

There are two types of configuration substitution.

Substitution from settings.php (settings override)


The settings.php file can replace configurations at the environment level. Just remember how we prohibited sending emails from development servers in Drupal 7:

 $conf['mail_system']['default-system'] = 'DevelMailLog'; 

In almost the same way it will look in Drupal 8:

 $config['system.mail']['interface']['default'] = 'devel_mail_log'; 

Module override


We can dynamically replace configurations from modules. To do this, use services that have a config.factory.override tag and implement the ConfigFactoryOverrideInterface class. You can find an example in the Language module, which translates some strings stored in configurations (this way, when you call Drupal::config(...)->get(...) , you actually get the translated string instead of the original one) .

Getting the source (not overridden) configurations


Sometimes we need initial configurations. Basically it is necessary for configuration forms (for example, so that the user can change the source strings, and not their translations). For this case, the core Drupal provides the class ConfigFormBase , which should be used instead of the standard FormBase . It has the ConfigFormBase::config() method, which returns the initial configurations and which, again, should be used instead of the usual Drupal::config() .

Another way is the Config::getRawData() method. And for more complex cases, look at the implementation of the ConfigFormBaseTrait::config() method .

Tip: Best Practices


When you work from a class that extends a base class, examine all the methods at your disposal (available from the parent classes) and use them instead of the globally available methods. The example above demonstrates how to get the initial configurations using the ::config() method when you are working from the child class ConfigFormBase . Another example: many classes have a built-in method ::t() , which should be used instead of the global function t() . There are always reasons for this, take a look at an example .

We respond to configuration changes


There are two ways:
  1. Subscribe to the events listed in the ConfigEvents class ( documentation ). For an example, see the implementation of the class Drupal\language\EventSubscriber\ConfigSubscriber ( documentation ).
  2. For more complex cases, you can use hook_config_import_steps_alter() . An example can be found in the Field module.

Configuration schema / metadata


You can describe your configuration with the help of configuration schemas, thereby making it understandable for Drupal. Let's start with an example.

 # file: core / modules / system / config / install / system.maintenance.yml
 message: '! site is currently under maintenance.  We should be back shortly.  Thank you for your patience. '
 langcode: en  
 
 # file: core / modules / system / config / schema / system.schema.yml
 system.maintenance: 
  type: mapping  
  label: 'Maintenance mode'
  mapping: 
    message: 
      type: text  
      label: 'Message to display when in maintenance mode'
    langcode: 
      type: string  
      label: 'Default language'
 
 # file: core / config / schema / core.data_types.schema.yml
 text: 
  type: string  
  label: 'Text'
  translatable: true  
 # ...
 string: 
  class: '\ Drupal \ Core \ TypedData \ Plugin \ DataType \ String'
  label: 'String'

From this data we can find out the purpose of the settings stored in the system.maintenance configuration, as well as their types:
  1. message is a string available for translation, displayed in the site maintenance mode
  2. langcode is a string indicating the language used for the site maintenance mode.

But more importantly, Drupal and other modules can also get this information.

There are so many types of data embedded in the core of Drupal, and you can create your own data types by expanding existing ones. Take a look at the Configuration schema / metadata section of the developer documentation to learn more.

Tip: Translations


The translatable property is used to mark string data types as available for translation. Such strings are automatically processed by the Language module. There are two basic "translatable" types of strings that you probably want to use:
  1. label : human-readable line, no markup, containing only one line of text
  2. text : human-readable string, may contain HTML markup and several lines of text

Configuration entities (configuration entities)


In short, configuration entities are entities that are stored as configurations. Therefore, I would recommend to get started with the Entity API documentation. After, you can look at the article Creating a configuration entity type in Drupal 8 from the developer documentation, containing a simple example. And when you have basic knowledge and you want more, you can familiarize yourself with the essence of ImageStyle from the Image module.

At last


I would like to say a big thank you to the people who started the Configuration Management Initiative and all the drupalists who worked hard to create such a smart feature in Drupal 8. The result of their work is great!

PS: There are already some modules that can help you with the configurations.

PSS: The Configuration management section from the developer documentation is a great place to get started quickly. However, be careful, because some of its parts are outdated and so far (until a stable release is released) do not correspond to reality.

Source: https://habr.com/ru/post/248629/


All Articles