The simplest way to provide routes is to define them in your module's routing YAML file. Not all routes can be known ahead of time and specified this way. By adding a route_callbacks entry in your routing YAML file as an array, callables that return a list of routes. For example adding:
route_callbacks:
- '\Drupal\mastering_drupal_8\Routing\TestRoutes::routes'
If we were to create the same route as above, that file would look like:
/**
* Defines dynamic routes.
*/
class TestRoutes {
/**
* {@inheritdoc}
*/
public function routes() {
$routes = array();
// Declares a single route under the name
'mastering_drupal_8.test_page'.
// Returns an array of Route objects.
$routes['mastering_drupal_8.test_page'] = new Route(
// Path to attach this route to:
'/mastering_drupal_8/test',
// Route defaults:
array(
'_controller' =>
'\Drupal\mastering_drupal_8\Controller\TestPageController::test',
),
// Route requirements:
array(
'_access' => 'TRUE',
)
);
return $routes;
}
}
Alternatively, you can return the routes using a RouteCollection object.
/**
* @file
* Contains \Drupal\mastering_drupal_8\Routing\TestRoutes.
*/
namespace Drupal\mastering_drupal_8\Routing;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Defines dynamic routes.
*/
class TestRoutes {
/**
* {@inheritdoc}
*/
public function routes() {
$routes = new RouteCollection();
// Declares a single route under the name
'mastering_drupal_8.test_page'.
// Returns an array of Route objects.
$route = new Route(
// Path to attach this route to:
'/mastering_drupal_8/test',
// Route defaults:
array(
'_controller' =>
'\Drupal\mastering_drupal_8\Controller\TestPageController::test',
),
// Route requirements:
array(
'_access' => 'TRUE',
)
);
$routes->add('mastering_drupal_8.test_page', $route);
return $routes;
}
}
Going through this process for a simple route to a controller is unnecessary. It is much simpler in most cases to just add the route to a routing YAML file. However, for cases like Views or Image where the routes are dependent on other factors, it allows the creation of those routes with specific URLs and access criteria.