The code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php namespace Drupal\my_module\Controller; use Drupal\Core\Controller\ControllerBase; use Drupal\Core\Entity\EntityTypeManager; // Example service class to load and use use Drupal\Core\Entity\Query\QueryFactory; // Another example service class to load and use use Symfony\Component\DependencyInjection\ContainerInterface; class MyModuleController extends ControllerBase { /** * @var QueryFactory */ protected $queryFactory; /** * @var EntityTypeManager */ protected $entityTypeManager; public static function create(ContainerInterface $container) { // Get your services here. return new static( $container->get('entity.query'), $container->get('entity_type.manager') ); } public function __construct(QueryFactory $query_factory, EntityTypeManager $entity_type_manager) { // Reference your services here for future use $this->queryFactory = $query_factory; $this->entityTypeManager = $entity_type_manager; } public function content() { // Do Controller stuff... $ids = $this->queryFactory->get('node')->condition('type', 'article')->pager(15)->execute(); $entities = $this->entityTypeManager->getStorage('node')->loadMultiple($ids); // etc... } } |
Additional Information
- Unlike service type class service dependency injection, there may be no need to implement an interface to be able to load the needed services, such as extending from
ControllerBase
. So if you are extending from a class which already has the dependency injection implementation, you can just override thecreate
and__construct
methods. Don’t forget to callparent
methods if needed. - Think of the
create
method as the model used by the__construct
of your class. - The
create
signature needs to respect the one of the implemented interface (use your IDE to check against the original declaration). - Originally made and tested on Drupal 8.2.x.
- A convenient list of core services can be found here: https://api.drupal.org/api/drupal/core%21core.services.yml/8.2.x (don’t forget to select the Drupal version if you are not on 8.2.x).
- Some classes such as ones extending
BlockBase
will need to implement interfaces to access this pattern:1class SomeCustomBlock extends BlockBase implements ContainerFactoryPluginInterface { ... }