[Drupal] Service dependency injection in a plugin type class

The code

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 and __construct methods. Don’t forget to call parent 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:
    class SomeCustomBlock extends BlockBase implements ContainerFactoryPluginInterface { ... }

Published by Dakwamine

Dakwamine, alias Quang-Minh Dang, né en 1987 en région parisienne. Un type sympa, pas bavard et pragmatique.