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

How to know allowed methods for one route in Symfony2?

我目前处于监听状态,我想在我的回复中 return 一些 headers。 $this->router->match($this->request->getPathInfo()); 我没有这方面的任何信息。但是我已经指定了方法:

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

终于可以不用"manually"解析路由文件了吗?

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

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

如果你有路线名称:

/** @var string $routeName */
/** @var Symfony\Component\HttpFoundation\Request $request */
$routeName = $request->attributes->get('_route');

并且您有 @router 服务(似乎此服务已注入到您的侦听器中):

// from the controller action.
/** @var Symfony\Bundle\FrameworkBundle\Routing\Router $router */
$router = $this->get('router');

//in your sample should be $this->router directly.

然后我们就可以通过路由集合获取路由实例及其信息:

/** @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();