#! code: Drupal 9: Altering Routes With The Route Subscriber Service

Creating services that listen events in Drupal is pretty straightforward; you just need to create and register a service class and let Drupal know what event you want to trigger on.

Altering routes in a Drupal site is also done through an event trigger, but in this case the implementation is slightly different. This is because Drupal takes care of the trigger setup and allows you to create an event subscriber that will automatically trigger when the routes are created.

In this article I will go through how to set up a route alter event subscriber, why the setup is slightly different from normal events, and what this event might be used for.

Altering Routes Using A Route Subscriber

Registering a route subscriber is done just like any other even subscriber with an entry in the module services YAML file. Adding a tag with the name of "event_subscriber" tells Drupal that this class should be included when events are triggered.

services: mymodule.route_subscriber: class: Drupal\mymodule\Routing\CustomRouteSubscriber tags: - { name: event_subscriber }

Next, we need to add the routing class to listen to the event. This can be put anywhere in the module, but its conventionally put into a Routing directory within the module src directory. Your module's directory structure should look something like this with the route subscriber in place.

Read more.

PubDate

Tags