Allow config to be lazily autowired into services and controllers

Created on 5 April 2024, 9 months ago

Problem/Motivation

At the moment the way to retrieve configuration in a service is by injecting the config factory and then getting the config from there. Sometimes we store the factory inside the constructor; other times we get the config from the factory and store that in the constructor - and in the latter case we don't always need the config, for example in PathBasedBreadcrumbBuilder:

    $this->config = $config_factory->get('system.site');

but if another breadcrumb builder takes priority, or we are on the front page, the config isn't even used.

But what if we could do something like this in constructors:

public function __construct(
  #[Config('system.site')]
  ImmutableConfig $config
)

Additionally, I suggest making ImmutableConfig (or a subclass of it) into a lazy proxy, so it only actually retrieves the config object from cache or storage when you read a value with $config->get().

This means that you don't need to concern yourself with the config factory at all for read-only cases - you only get the config that you need injected directly into your service/controller/etc, and lazy-loading the config on demand improves performance in the cases where the config is not actually used.

Steps to reproduce

Proposed resolution

Introduce LazyConfig, prototype example:

class LazyConfig extends ImmutableConfig {

  protected ImmutableConfig $config;

  public function __construct(
    protected ConfigFactoryInterface $configFactory,
    string $name,
  ) {
    $this->name = $name;
  }

  public function get($key = '') {
    $this->config ??= $this->configFactory->get($this->name);
    return $this->config->get($key);
  }

}

Add support for a new attribute to the DI container and AutowireTrait.

Remaining tasks

User interface changes

API changes

Data model changes

Release notes snippet

πŸ“Œ Task
Status

Active

Version

11.0 πŸ”₯

Component
ConfigurationΒ  β†’

Last updated about 17 hours ago

Created by

πŸ‡¬πŸ‡§United Kingdom longwave UK

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024