路由器匹配 url 与参数

router match url with parameters

在我的 Symfony2 项目中,我有一个 route 参数:

my_route:
    pattern:  /{param1}/{param2}
    defaults: { _controller: MyBundle:MyController:myAction }

并且在操作 myAction 中我得到了 url 并且当我尝试通过匹配 url 来获取相应的路线时我得到了这个错误:

 500 Internal Server Error - ResourceNotFoundException 

然后堆栈跟踪显示此消息:

1. in C:\Users\itaziny\git\Symfony\app\cache\dev\appDevUrlMatcher.php at line 459 

  throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();

这是我的代码:

public function myActionAction(Request $request) {
   $url = $request->headers->get('referer');
   $router = $this->get('router');
   $route = $router->match($url);
   // Some code...

   if (route == "my_route") {
       // redirect to the pag: my_route
   }
   else {
      //redirect to the page who called this action
   }
}

操作:myAction 从 2 个不同的页面调用,我必须重定向到调用操作的页面 myAction

我终于在这里找到了答案: Symfony2: Redirecting to last route and flash a message?

所以我所做的就是这样:

$uri = $request->headers->get('referer');
$baseUrl = $request->getBaseUrl();
$lastPath = substr($uri, strpos($uri, $baseUrl) + strlen($baseUrl));

$route = $this->get('router')->match($lastPath);
if ($route['_route'] == "my_route") {
    // redirect to the pag: my_route
}
else {
  //redirect to the page who called this action

}