To generate a dynamic routes, we start off with the route_callbacks method.
To begin, you just add the method in your routing.yml with the callback to your class and method:
route_callbacks:
- '\Drupal\mymodule\Routing\MyModuleRoutes::routes'
Then you just need to make a Routing class and slap in your logic. Basically you are creating the YAML version of the typical route in PHP in the routes method.
in this class also I Inject config.factory service to get dynamic params from config form.
<?php
namespace Drupal\mymodule\Routing;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
/**
* Class MyModuleRoutes
* @package Drupal\mymodule\Routing
*/
class MyModuleRoutes implements ContainerInjectionInterface {
/**
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* MyModuleRoutes constructor.
* @param ConfigFactoryInterface $config_factory
*/
public function __construct(ConfigFactoryInterface $config_factory) {
$this->config = $config_factory->get('mymodule.settings');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory')
);
}
/**
* {@inheritdoc}
*/
public function routes()
{
$routes = [];
$pid = 1;
// $path = '/example';
$path = $this->config->get('path_page');
$routes['mymodule.page_' . $pid] = new Route(
$path,
[
'_controller' => '\Drupal\mymodule\Controller\MyModuleController::index',
'_title' => 'Hello'
],
[
'_permission' => 'access content',
]
);
return $routes;
}
}
As you can see this is basically adding another layer between the routing.yml and the Controller. Here is what our Controller looks like this:
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
class MyModuleController extends ControllerBase {
/**
* @return string[]
*/
public function index() {
return [
'#markup' => 'Hello world ?',
];
}
}