4

Apparently by default ControllerBase::config() returns \Drupal\Core\Config\ImmutableConfig object. How can I instantiate the controller class to make it use \Drupal\Core\Config\Config instead (which is mutable)?

I know I can do this inside the controller:

$config = \Drupal::service('config.factory')->getEditable('loremipsum');

However this is not the nicest solution. Besides, is there any reason for using ImmutableConfig by default?

1 Answer 1

9

There are two other ways to inject dependencies into a controller, and a third alternative.

1. Implement ContainerInjectionInterface

This does technically add a dependency to the container. In a unit test, the container would need to be set with \Drupal::setContainer() with a mock object of the config factory and config object.

`

  public static function create(\Symfony\Component\DependencyInjection\ContainerInterface $container) {
    return new static($container->get('config.factory'));
  }

  public function __construct(\Drupal\Core\Config\ConfigFactoryInterface $config_factory) {
    $config = $this->config_factory->getEditable('loremipsum');
  }

`

2. Make the controller a service.

This is recommended by all of the Symfony developers that I have asked, and none have been concerned by any performance impact of making all of Drupal's routes use services.

This is subjective, and there is some contention about the practice.

3. Use a Form class that extends ConfigFormBase instead.

But, why would a controller want MutableConfig instead of ImmutableConfig? A Form class extending ConfigFormBase instead. A form is probably the best place to modify configuration values such as a class that extends ConfigFormBase.

1
  • 1
    I'm also not a fan of Controller as a service solution. And yes, I'm also one of the "thin controller" advocates. However in this case I needed something for testing and I was surprised that controllers get ImmutableConfig on purpose. Dec 23, 2015 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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