Laravel:将任意URL解析为相应的Controller / Route?

时间:2015-09-28 17:22:46

标签: php laravel routing routes

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

...
Route::get('/foobar/{parameter}', 'MyFoobarController@index');
...

我如何"反向解析/解析" URL(like http://localhost/foobar/foo)再次进入此配置的控制器(MyFoobarController)?请注意:我不是在讨论当前的请求,而是一种将Laravel中映射的任何URL解析为相应的Controller和Action(代码中任何位置,与当前请求无关)的一般方法。谢谢!

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

2 个答案:

答案 0 :(得分:4)

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

#new

您可以使用Route::get('/foobar', 'MyFoobarController@index'); 外观来获取所有已注册路线的列表:

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; } } 方法将返回一个数组,其中包含有关为该路由映射的操作的相关信息。您可以查看Illuminate\Routing\Route API,了解有关在匹配路线后可以使用哪些方法的更多信息。

答案 1 :(得分:0)

   private function getMatchRoutes($request)
    {
        $referer = $request->header('Referer');
        $refererPath  = parse_url($referer,PHP_URL_PATH);
        $routes = Route::getRoutes()->getRoutes();
        $matchedRoute = null;
        foreach ($routes as $route) {
            $route->compiled = (new RouteCompiler($route))->compile();
            if (is_null($route->getCompiled())) continue;
            if (preg_match($route->getCompiled()->getRegex(), rawurldecode($refererPath))) {
                $matchedRoute =  $route;
            }
        }
        if (is_null($matchedRoute)) return $matchedRoute;
        return explode('@',$matchedRoute->getActionName())[0];
    }

我上面写的代码是从请求引用者获取控制器/动作,您可以将其替换为有效的url,尝试一下,可能会有所帮助~~~

相关问题