The code
1 2 3 4 5 6 7 8 9 10 11 |
services: my_module.event_subscriber: # Your service class class: Drupal\my_module\Entity\EventSubscriber\MyModuleSubscriber # Add your services to load here in the array arguments: ['@current_user'] tags: # For this example, I am making an event subscriber class - { name: event_subscriber } |
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 |
<?php namespace Drupal\my_module\Entity\EventSubscriber; use Drupal\Core\Session\AccountProxy; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; class MyModuleSubscriber implements EventSubscriberInterface { /** * Current user service. * @var AccountProxy */ protected $currentUser; public function __construct(AccountProxy $current_user) { // Reference the current_user service $this->currentUser = $current_user; } static function getSubscribedEvents() { // Stuff related to events subscribing in Drupal $events[KernelEvents::REQUEST][] = ['kernel_request']; return $events; } /** * @param GetResponseEvent $event */ public function kernel_request(Event $event) { // Do stuff here, using $this->currentUser } } |
Additional Information
- Declare the services your class will use in the .services.yml file of your module.
- Unlike plugin type class service dependency injection, there is no
create
method to define the needed services. - The
__construct
signature needs to respect the declared arguments from the .services.yml file. - 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).
- If you are curious about event subscribing in the Drupal world, please check this article: [Drupal] Create an event subscriber.