[英]Symfony 2: How to get route defaults by route name?
是否可以通过名称检索某条路线的信息,或获取所有路线的列表?
我需要能够在任何路由的defaults
值中获取_controller
值,而不仅仅是当前路由。
这可能吗?怎么样?
PS:我发现我可以获得使用YAML路线的路径,但是重新分析它似乎是不必要的和沉重的。
我很擅长回答自己的问题..
要获取路由,请在路由器上使用getRouteCollection()
( $this -> get('router') -> getRouteCollection()
在控制器内),然后获取RouteCollection实例,您可以在其上all()
或get($name)
。
正如我在上面的评论中所描述的那样, Router::getRouteCollection
非常慢,不适合在生产代码中使用。
因此,如果你真的需要它,你必须通过它来破解它。 请注意, 这将是hackish :
直接访问转储的路由数据
为了加速路由匹配,Symfony将所有静态路由编译为一个大的PHP类文件。 此文件由Symfony\\Component\\Routing\\Generator\\Dumper\\PhpGeneratorDumper
并声明一个Symfony\\Component\\Routing\\Generator\\UrlGenerator
,它将所有路由定义存储在名为$declaredRoutes
的私有静态中。
$declaredRoutes
是由路由名称索引的已编译路由字段数组。 除其他外(见下文),这些字段还包含路由默认值。
为了访问$declaredRoutes
我们必须使用\\ ReflectionProperty 。
所以实际的代码是:
// If you don't use a custom Router (e.g., a chained router) you normally
// get the Symfony router from the container using:
// $symfonyRouter = $container->get('router');
// After that, you need to get the UrlGenerator from it.
$generator = $symfonyRouter->getGenerator();
// Now read the dumped routes.
$reflectionProperty = new \ReflectionProperty($generator, 'declaredRoutes');
$reflectionProperty->setAccessible(true);
$dumpedRoutes = $reflectionProperty->getValue($generator);
// The defaults are at index #1 of the route array (see below).
$routeDefaults = $dumpedRoutes['my_route'][1];
路径数组的字段
每个路由的字段由上面提到的Symfony\\Component\\Routing\\Generator\\Dumper\\PhpGeneratorDumper
如下所示:
// [...]
$compiledRoute = $route->compile();
$properties = array();
$properties[] = $compiledRoute->getVariables();
$properties[] = $route->getDefaults();
$properties[] = $route->getRequirements();
$properties[] = $compiledRoute->getTokens();
$properties[] = $compiledRoute->getHostTokens();
$properties[] = $route->getSchemes();
// [...]
因此,要访问其要求,您将使用:
$routeRequirements = $dumpedRoutes['my_route'][2];
底线
我查看了Symfony手册,源代码,论坛,stackoverflow等,但仍然无法找到更好的方法。
这是残酷的,忽略了API,并可能在未来的更新中中断(虽然它在最近的Symfony 4.1中没有改变: GitHub上的PhpGeneratorDumper )。
但它足够短而快,足以用于生产。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.