4

In Drupal when we are working with read-only config we use

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

Why this static call for read-only object?

and when we use working with a config where both read and write is possible. we use this service 'config.factory'

$config = \Drupal::service('config.factory')->getEditable('system.performance');
$config->set('cache.page', ['enabled' => 1, 'max_age' => 5]);

what leads to this design?

0
5

This change record explains it all: Configuration objects by default are immutable.

ConfigFactoryInterface::get() no longer returns configuration objects that can be saved. This is to ensure that configuration overrides do not get into active configuration. Configuration overrides are, for example, global overrides set in settings.php or translations provided by the locale module. If you need to get a configuration object that can be saved, use ConfigFactoryInterface::getEditable(). Objects returned by that method will not have overrides applied.

Previously

// Just get the site name (with overrides).
$site_name = \Drupal::config('system.site')->get('name');

// Set the site name.
\Drupal::config('system.site')->set('name', 'My fantastic site')->save();

Now

// Just get the site name (with overrides, same as before).
$site_name = \Drupal::config('system.site')->get('name');

// Set the site name.
\Drupal::configFactory()->getEditable('system.site')->set('name', 'My fantastic site')->save();

Are you also/alternatively asking why there's a Drupal::config method, but not a Drupal::configFactory method, i.e. why do you have to use the generic Drupal::service method for the second one?

If so, that's simply because the shortcut methods exposed on the Drupal class are for the most regularly used services. The config service is used in procedural code a lot more than config.factory, so there's no shortcut method for it. There are hundreds (thousands?) of services throughout the system so providing a method for each would be overkill

1
  • Thanks, that explains everything, also you resolved my confusion on static call vs service call. Now everything makes more sense !! – riju.srk Jan 6 '19 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.