Instructions
I will be creating a dedicated module using Drupal Console for this event subscriber. But feel free to use your own if you already have one! (don’t forget to backup)
- Access the drupal root folder in command line.
- Generate a new module:
123456789101112131415161718192021222324252627282930313233343536373839dakwamine@debian-drupal:/var/www/html/drupal$ drupal generate:moduleEnter the new module name:> Test ModuleEnter the module machine name [test_module]:>Enter the module Path [/modules/custom]:>Enter module description [My Awesome Module]:>Enter package name [Custom]:>Enter Drupal Core version [8.x]:>Do you want to generate a .module file (yes/no) [yes]:> noDefine module as feature (yes/no) [no]:>Do you want to add a composer.json file to your module (yes/no) [yes]:> noWould you like to add module dependencies (yes/no) [no]:>Do you confirm generation? (yes/no) [yes]:>Generated or updated filesSite path: /var/www/html/drupal1 - modules/custom/test_module/test_module.info.yml - Generate the event subscriber. We will subscribe to the
kernel.request
event:
123456789101112131415161718192021222324252627282930313233343536373839dakwamine@debian-drupal:/var/www/html/drupal$ drupal generate:event:subscriberEnter the module name [admin_toolbar]:> test_moduleEnter the service name [test_module.default]:> test_module.event_subscriber_exampleClass name [DefaultSubscriber]:> TestModuleExampleSubscriberType the event name or use keyup or keydown.This is optional, press enter to continueEnter event name [ ]:> kernel.requestCallback function name to handle event [kernel_request]:>Enter event name [ ]:>Do you want to load services from the container (yes/no) [no]:>Do you confirm generation? (yes/no) [yes]:>Generated or updated filesSite path: /var/www/html/drupal1 - modules/custom/test_module/src/EventSubscriber/TestModuleExampleSubscriber.php2 - modules/custom/test_module/test_module.services.ymlcache:rebuildRebuilding cache(s), wait a moment please.[OK] Done clearing cache(s). - Current state:
-
123456.├── src│ └── EventSubscriber│ └── TestModuleExampleSubscriber.php├── test_module.info.yml└── test_module.services.yml
-
12345name: Test Moduletype: moduledescription: My Awesome Modulecore: 8.xpackage: Custom
-
123456services:test_module.event_subscriber_example:class: Drupal\test_module\EventSubscriber\TestModuleExampleSubscriberarguments: []tags:- { name: event_subscriber }
-
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950<!--?phpnamespace Drupal\test_module\EventSubscriber;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\EventDispatcher\Event;/*** Class TestModuleExampleSubscriber.** @package Drupal\test_module*/class TestModuleExampleSubscriber implements EventSubscriberInterface {/*** Constructor.*/public function __construct() {}/*** {@inheritdoc}*/static function getSubscribedEvents() {// Array structure recommended in Drupal official docs$events['kernel.request'][] = ['kernel_request'];// Generated by Drupal Console, tested, works the same for now//$events['kernel.request'] = ['kernel_request'];// kernel.request has a constant which can be used as the following//$events[KernelEvents::REQUEST][] = ['kernel_request'];return $events;}/*** This method is called whenever the kernel.request event is* dispatched.** @param GetResponseEvent $event*/public function kernel_request(Event $event) {drupal_set_message('Event kernel.request thrown by Subscriber in module test_module.', 'status', TRUE);}}</pre-->
-
- Install the module using either
drupal module:install
ordrush pm-enable
:
12345678910111213dakwamine@debian-drupal:/var/www/html/drupal$ drupal module:install test_moduleInstalling module(s) test_module[OK] The following module(s) were installed successfully: test_modulecache:rebuildRebuilding cache(s), wait a moment please.[OK] Done clearing cache(s). - Now, refresh your web page and on each request received server side, a message will tell you the event occurred!
Additional Information
- Instructions made on Drupal 8.2.x.
- Using Drupal Console, you can easily inject services such as the current_user one by answering yes when it asks if you want to load services from the container. Please check this article about service dependency injection: [Drupal] Service dependency injection in a service type class.
- After editing your files, remember to run a cache rebuild either with
drupal cache:rebuild
ordrush cache-rebuild
. - Events documentation entry point: Events on Drupal 8. You will find a few core events here.
- The callback function’s name can be changed to whatever you want.