Laravel:解析任意URL到其相应的Controller / Route?

Tim*_*idt 5 php routing routes laravel

鉴于我有一个这样映射的任意URL(以及许多其他URL)

...
Route::get('/foobar/{parameter}', 'MyFoobarController@index');
...
Run Code Online (Sandbox Code Playgroud)

如何再次将URL(like http://localhost/foobar/foo)反向解析/解析到此已配置的控制器(MyFoobarController)中?请注意:我不是在谈论当前的请求,而是一种通用的方法来解析Laravel中映射到其相应的Controller and Action(在代码中与当前请求无关的任何地方)的任何URL。谢谢!

更新:还应该正确匹配其中包含参数的路由。

Bog*_*dan 3

您可以将 URL 路径与添加到路由器的路径进行比较。让我们以你的例子为例:

Route::get('/foobar', 'MyFoobarController@index');
Run Code Online (Sandbox Code Playgroud)

您可以使用Route外观来获取所有已注册路线的列表:

// This is your URL as a string
$url = 'http://localhost/foobar';

// Extract the path from that URL
$path = trim(parse_url($url, PHP_URL_PATH), '/');

// Iterate over the routes until you find a match
foreach (Route::getRoutes() as $route) {
    if ($route->getPath() == $path) {
        // Access the action with $route->getAction()
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

getAction方法将返回一个数组,其中包含有关为该路由映射的操作的相关信息。您可以查看Illuminate\Routing\RouteAPI,了解匹配路线后可以使用哪些方法的更多信息。