5

Documentation is proposed to use injection in constructor instead of using \Drupal::service(). Why?

Example with injection:

class MyController extends ControllerBase implements ContainerInjectionInterface {
  protected $database;
  public function __construct(Connection $database) {
    $this->database = $database;
  }
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database')
    );
  }
}

Example without injection (it is easier):

class MyController extends ControllerBase {
  protected $database;
  public function __construct() {
    $this->database = \Drupal::service('database');
    // or
    $this->database = \Drupal::database();
  }
}
5
  • 1
    What is dependency injection should cover it. The Symfony docs are worth a read too. Short answer: for testing
    – Clive
    Commented Jan 23, 2014 at 0:43
  • It's the same as drupal.stackexchange.com/questions/100332/…
    – user21641
    Commented Jan 23, 2014 at 10:46
  • But methods in ControllerBase still use \Drupal::getContainer(), why this can not be done in the MyController?
    – xandeadx
    Commented Jan 23, 2014 at 11:44
  • @xandeadx Probably because it's abstract and can't be instantiated, negating the possibility of injecting the container. But maybe not, don't forget code freeze hasn't happened yet, things are still going through a lot of changes
    – Clive
    Commented Jan 23, 2014 at 16:30
  • ControllerBase is a convenience class. It uses a private method to provide commonly needed services. This question really boils down to "Why use dependency injection", and that's not a Drupal-specific question. Commented Feb 6, 2014 at 1:45

1 Answer 1

1

As soon as you start to test MyController you will run into problems

The test harness must be able to instantiate the minimum amount of stuff around your class to still be able to put it through its paces.

It is easier to mock up and inject a simple container.. rather provide \Drupal::service as it will rapidly spiral out of control and your test harness will have to provide a full drupal environment.

In more formal language you have just "tightly coupled" MyController to the drupal eco-system, and so you have made your code less reusable.

1
  • This is understandable. It is unclear why ControllerBase still use \Drupal::service
    – xandeadx
    Commented Apr 4, 2014 at 21:33

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.