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();
}
}