簡體   English   中英

在前綴根路徑中找不到路由

[英]Route Not Found In Prefix Root Path

我正在嘗試在我的項目中設置 symfony/路由組件..

事情 go 很好,但是當我為路由定義前綴時,它會為該前綴的根路徑拋出 route not found 異常。

例如,假設我有一堆管理路由。 我沒有在每條路由上定義“admin”關鍵字,而是為所有這些設置了前綴路由。 所以我的儀表板路徑從"/admin"變成了"/" " 。 現在它拋出找不到路由錯誤..

當我檢查路線 collections 時。 儀表板路徑似乎為"/admin/" 它與REQUEST_URI不匹配

我是否設置了組件不好,或者我需要做一些注意事項?

這是 RouteProvider 的一部分

foreach (scanDirectory(ROOT_PATH . "/routes") as $file) {
    $subCollection = new RouteCollection();
    $filepath = ROOT_PATH . "/routes/" . $file;
    $routes = Yaml::parseFile($filepath);

    $prefix = "api";

    if (array_key_exists("prefix", $routes)){
        $prefix =  $routes["prefix"];
        unset($routes["prefix"]);
    }

    foreach ($routes as $name => $route) {
        $parameters = (new RouteParser($route))->parse();
        $subCollection->add(
            $name,
            new Route(...$parameters)
        );
    }
    $subCollection->addPrefix($prefix);
    $subCollection->addOptions([
        "trailing_slash_on_root" => false
    ]);
    $collection->addCollection($subCollection);
 }

我在路由器組件中戳了一下。 trailing_slash_on_root 功能是作為加載程序的一部分實現的。 所以我認為你需要在你的路由文件中設置它。 您沒有提供管理路由文件的示例,所以我不肯定。 通常,我希望只看到加載的主路由文件,該文件又會加載單獨的路由集,例如您的管理路由。

但是,以您發布的代碼為例,我們可以實現 trailing_slash_on_root 使用的相同過程。 基本上,在所有處理發生后,我們顯式刪除儀表板路由的尾部斜杠。 這是一個完整的獨立工作示例,主要取自路由組件文檔:

$rootCollection = new RouteCollection();
$adminCollection = new RouteCollection();

$route = new Route('/users',['_controller' => 'admin_users_controller']);
$adminCollection->add('admin_users',$route);

$route = new Route('/',['_controller' => 'admin_dashboard_controller']);
$adminCollection->add('admin_dashboard',$route);

$adminCollection->addPrefix('/admin'); # This actually adds the prefix

# *** Explicitly tweak the processed dashboard route ***
$route = $adminCollection->get('admin_dashboard');
$route->setPath('/admin');

$rootCollection->addCollection($adminCollection);

$context = new RequestContext('/');

// Routing can match routes with incoming requests
$matcher = new UrlMatcher($rootCollection, $context);
$parameters = $matcher->match('/admin/users');
var_dump($parameters);

$parameters = $matcher->match('/admin');
var_dump($parameters);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM