Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

Previously registering dynamic routes was full of boilerplate code. Now it's easier and you don't have to deal with the event system anymore.

To alter a route, you just extend the \Drupal\Core\Routing\RouteSubscriberBase class which provides an alterRoutes method. To define dynamic routes you declare a route callback in the .routing.yml file.

Before

class RouteSubscriber implements EventSubscriberInterface {
  
  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[RoutingEvents::DYNAMIC] = 'dynamicRoutes';
    $events[RoutingEvents::ALTER] = 'alterRoutes';
    return $events;
  }

  public function alterRoutes(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();

    // Do something ...
  }

  public function dynamicRoutes(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();

    // Do something ...
  }

}

After

Alter a route by extending RouteSubscriberBase.
See the API documentation Altering existing routes for implementation details.

use \Drupal\Core\Routing\RouteSubscriberBase;

class RouteSubscriber extends RouteSubscriberBase {

  public function alterRoutes(RouteCollection $collection) {
    // Do something ...
  }

}

Dynamic routes use a yaml file to declare a route callback and a route callback class.
See the API documentation Providing dynamic routes for implementation details.

# @file example.routing.yml
route_callbacks:
  - '\Drupal\example\Routing\ExampleRoutes::routes'
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ExampleRoutes {

  /**
   * Dynamic route callback.
   *
   * @return \Symfony\Component\Routing\Route[]
   *   An array of route objects.
   */
  public function routes() {
    // Do something ...

    return $routes;
  }

}
Impacts: 
Module developers

Comments

albert volkman’s picture

I believe the new code example should be:

<?php
use \Drupal\Core\Routing\RouteSubscriberBase;

class RouteSubscriber extends RouteSubscriberBase {

  public function routes(RouteCollection $collection) {
    // Do something ...
  }

  public function alterRoutes(RouteCollection $collection, $module) {
    // Do something ...
  }

}
?>
sutharsan’s picture

Thanks for reporting (but you may edit too). Now updated.

-- Erik