When Drupal's route system is rebuilt because of a module being enabled or caches being rebuilt, an event is fired that allows modules to alter routes defined statically in YAML or dynamically. This involves implementing an event subscriber by extending \Drupal\Core\Routing\RouteSubscribeBase, which subscribes the RoutingEvents::ALTER event.
Create a src/Routing/RouteSubscriber.php file in your module. It will hold the route subscriber class:
<?php
namespace Drupal\mymodule\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
public function alterRoutes(RouteCollection $collection) {
// Change path of mymodule.mypage to use a hyphen
if ($route = $collection->get('mymodule.mypage')) {
$route->setPath('/my-page');
}
}
}
The preceding code extends RouteSubscribeBase and implements the alterRoutes() method. We make an attempt to load the mymodule.mypage route, and, if it exists, we change its path to my-page. Since objects are always passed by reference, we do not need to return a value.
For Drupal to recognize the subscriber, we will need to describe it in the module's services.yml file. In the base directory of your module, create a mymodule.services.yml file and add the following code:
services:
mymodule.route_subscriber:
class: Drupal\mymodule\Routing\RouteSubscriber
tags:
- { name: event_subscriber }
This registers our route subscriber class as a service to the container so that Drupal can execute it when the event is fired.