The routing system allows modules to define routes programmatically. This can be accomplished by providing a routing_callbacks key that defines a class and method that will return an array of the \Symfony\Component\Routing\Route objects.
In the module's routing.yml, you will define the routing callbacks key and related class:
route_callbacks: - '\Drupal\mymodule\Routing\CustomRoutes::routes'
The \Drupal\mymodule\Routing\CustomRoutes class will then have a method named routes, which returns an array of Symfony route objects:
<?php
namespace Drupal\mymodule\Routing;
use Symfony\Component\Routing\Route;
class CustomRoutes {
public function routes() {
$routes = [];
// Create mypage route programmatically
$routes['mymodule.mypage'] = new Route(
// Path definition
'mypage',
// Route defaults
[
'_controller' => '\Drupal\mymodule\Controller\MyPageController::customPage',
'_title' => 'My custom page',
],
// Route requirements
[
'_permission' => 'access content',
]
);
return $routes;
}
}
If a module provides a class that interacts with routes, the best practice is to place it in the routing portion of the module's namespace. This helps you identify its purpose.
The invoked method is expected to return an array of initiated route objects. The route class takes the following arguments:
- Path: This represents the route
- Defaults: This is an array of default values
- Requirements: This is an array of required validators
- Options: This is an array that can be passed and used optionally