Quickly create an instance of a class that uses Drupal's Dependency Injection

Posted by patrick on Mon, 02/13/2017 - 11:04

Sometimes you might want to get an instance of a class that implements ContainerInjectionInterface in unusual places. Let's imagine, that we have an ExampleController class, that extends ControllerBase and want an instance of it somewhere. It's actually pretty simple. We just get the container and create one:

use Drupal\example\Controller\ExampleController;
  
$container = \Drupal::getContainer(); 
$exampleController = ExampleController::create($container);

Et voilĂ !

Systems
Drupal 8/9