【问题标题】:Dynamic routes are not re-created after cache is cleared清除缓存后不会重新创建动态路由
【发布时间】: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'

【问题讨论】:

    标签: drupal drupal-8


    【解决方案1】:

    似乎路由已缓存(而不是通过清除缓存来清除??)。
    通过docs here判断,可以设置路由不缓存。
    例如。

    $routes[$routeName] = new Route(
      '/' . $alias . '.pdf',
      [
        '_controller' => '\Drupal\demo_module\Controller\DemoModuleController::getData',
        '_title' => 'Demo Data',
      ],
      [
        '_permission' => 'access content',
      ],
      [
        'no_cache' => TRUE
      ]
    );
    

    我没有测试上面的代码,但这是我会尝试的第一件事,Route class docs here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 2011-07-13
      相关资源
      最近更新 更多