Please refer New routing system to know more about Drupal 7 vs Drupal 8. This change record explains the dynamic routing changes since initial implementation in Drupal 8.
Previously, if you wanted to create routes dynamically, you'd need to create a class that extends RouteSubscriberBase
and create a service definition tagged with 'event_subscriber'
for it to be picked up.
Now you can declare a dynamic routing method directly in your routing.yml
file that returns an array of \Symfony\Component\Routing\Route
objects or a \Symfony\Component\Routing\RouteCollection
object.
Example snippet from my_module.routing.yml
:
route_callbacks:
- '\Drupal\mymodule\Routing\SomeClass::routes'
Before
Takes a RouteCollection
and modifies it, returning nothing.
Only $collection->add()
should be used here, but all methods are available.
protected function routes(RouteCollection $collection) {
$directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
$route = new Route(
'/' . $directory_path . '/styles/{image_style}/{scheme}',
array(
'_controller' => 'Drupal\image\Controller\ImageStyleDownloadController::deliver',
),
array(
'_access' => 'TRUE',
)
);
$collection->add('image.style_public', $route);
}
After
No parameters, returns a traversable keyed by route name, containing Route objects.
This can either be an associative array keyed by route name of Route objects:
public function routes() {
$routes = array();
$routes['mymodule.route_name'] = new Route(
'/mymodule/route',
array(
'_form' => '\Drupal\mymodule\Form\MyForm',
),
array(
'_permission' => 'access content',
)
);
return $routes;
}
Or return a RouteCollection object:
public function routes() {
$route_collection = new RouteCollection();
$route = new Route(
'/mymodule/route',
array(
'_form' => '\Drupal\mymodule\Form\MyForm',
),
array(
'_permission' => 'access content',
)
);
$route_collection->add('mymodule.route_name', $route);
return $route_collection;
}
If a RouteCollection
needs to be modified outside of adding routes, an EventSubscriber
for RoutingEvents::ALTER
should be used.