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 the create […]