如何在 Symfony2 中获取控制器的所有路由列表?
问题描述:
我有一个实现所有路由/URL的控制器.我想为所有帮助页面提供一个通用索引.
I have a controller which implements all routes/URL(s). I had the idea to offer a generic index over all help-pages.
有没有办法在 Symfony2
中获取控制器(从控制器内)定义的所有路由?
Is there a way to get all routes defined by a controller (from within a controller) in Symfony2
?
答
您可以获取所有路由,然后从中创建一个数组,然后将该控制器的路由传递给您的树枝.
You could get all of the routes, then create an array from that and then pass the routes for that controller to your twig.
这不是一个漂亮的方式,但它有效..无论如何对于 2.1..
It's not a pretty way but it works.. for 2.1 anyways..
/** @var $router SymfonyComponentRoutingRouter */
$router = $this->container->get('router');
/** @var $collection SymfonyComponentRoutingRouteCollection */
$collection = $router->getRouteCollection();
$allRoutes = $collection->all();
$routes = array();
/** @var $params SymfonyComponentRoutingRoute */
foreach ($allRoutes as $route => $params)
{
$defaults = $params->getDefaults();
if (isset($defaults['_controller']))
{
$controllerAction = explode(':', $defaults['_controller']);
$controller = $controllerAction[0];
if (!isset($routes[$controller])) {
$routes[$controller] = array();
}
$routes[$controller][]= $route;
}
}
$thisRoutes = isset($routes[get_class($this)]) ?
$routes[get_class($this)] : null ;