【发布时间】:2021-05-10 19:30:25
【问题描述】:
我正在尝试根据从第三方服务(也是另一个 Drupal 网站)提取的数据创建动态路由。启用包含此动态路由的自定义模块时会创建路由,但清除缓存时不会重新创建这些动态路由。源 Drupal 网站公开 Drupal 内容,此目标站点需要使用源 Drupal 站点的路径别名创建路由。
我们将非常感谢任何有助于更好实施的指南/提示。
这就是我创建动态路由的方式:
<?php
namespace Drupal\demo_module\Routing;
use Symfony\Component\Routing\Route;
/**
* Defines dynamic routes.
*/
class DynamicRoutes {
/**
* {@inheritdoc}
*/
public function routes() {
$routes = [];
// This is the service for pulling data. It pulls data from another drupal sites.
$demoService = \Drupal::service('demo_module.service');
// Just checks if service is available.
if ($demoService->isAvailable()) {
try {
$demoData = $demoService->getDataFromServices();
if (isset($demoData['data']) && count($demoData['data']) > 0) {
foreach ($demoData['data'] as $data) {
$alias = $data['attributes']['path']['alias'];
if (isset($alias) && !empty($alias)) {
$route_provider = \Drupal::service('router.route_provider');
$routeName = 'demo_module.' . ltrim($alias, '/');
$exists = count($route_provider->getRoutesByNames([$routeName])) === 1;
if (!$exists) {
// Want to add .pdf at the end of route name. So the route name would be the path alias from the source drupal site plus .pdf appended.
$routes[$routeName] = new Route(
'/' . $alias . '.pdf',
[
'_controller' => '\Drupal\demo_module\Controller\DemoModuleController::getData',
'_title' => 'Demo Data',
],
[
'_permission' => 'access content',
]
);
}
}
}
}
}
catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}
return $routes;;
}
}
这就是将路由添加到demo_module.routing.yml的方式
route_callbacks:
- '\Drupal\demo_module\Routing\DynamicRoutes::routes'
【问题讨论】: