如何在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.
是否有办法获取控制器定义的所有路径(来自a控制器)在 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 \Symfony\Component\Routing\Router */
$router = $this->container->get('router');
/** @var $collection \Symfony\Component\Routing\RouteCollection */
$collection = $router->getRouteCollection();
$allRoutes = $collection->all();
$routes = array();
/** @var $params \Symfony\Component\Routing\Route */
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 ;