如何知道Symfony2中一条路线的允许方法?

如何知道Symfony2中一条路线的允许方法?,symfony,routes,http-method,Symfony,Routes,Http Method,我目前在侦听器中,我想在响应中返回一些标题$this->router->match($this->request->getPathInfo())我没有这方面的任何信息。不过,我已指明方法: api_v2_spokespeople_collection: path: /spokespeople defaults: { _controller: "APIBundle:v2/Spokesperson:getCollection" } methods: [GET, OPTIONS] 最终

我目前在侦听器中,我想在响应中返回一些标题<代码>$this->router->match($this->request->getPathInfo())我没有这方面的任何信息。不过,我已指明方法:

api_v2_spokespeople_collection:
  path: /spokespeople
  defaults: { _controller: "APIBundle:v2/Spokesperson:getCollection" }
  methods:  [GET, OPTIONS]

最终是否可以不必“手动”解析路由文件?

据我所知,您将获得当前路由允许的方法。如果是,则:

$route = $this->request->get('_route');
$methods = $route->getMethods();

如果您有路由名称:

/** @var string $routeName */
/** @var Symfony\Component\HttpFoundation\Request $request */
$routeName = $request->attributes->get('_route');
您有
@router
服务(似乎此服务已注入您的侦听器):

然后我们可以通过route collection获取路由实例及其信息:

/** @var Symfony\Component\Routing\Route $route */
$route = $router->getRouteCollection()->get($routeName);
最后,您需要调用
getMethods()
以了解定义的方法:

/** @var string[] $methods */
$methods = $route->getMethods(); // e.g. array('GET', 'POST')

一行:

$methods = $this->router->getRouteCollection()->get($request->get('_route'))->getMethods();

我无法使用此选项,因为当我转储
$route
时,我得到了
null
。这真的很奇怪。@fnev.eu请确保在路由之后执行侦听器listener@WouterJ是的,好多了!但是$route现在是一个字符串。当我尝试使用router->match()方法时,我得到了一个没有方法的数组…AFAIK
$request->get(“'u route')
总是(默认情况下)返回一个字符串):/?正是我需要的。谢谢!
$methods = $this->router->getRouteCollection()->get($request->get('_route'))->getMethods();