是否可以按名称检索有关特定路由的信息,或获取所有路由的列表?
我需要能够以defaults
方式获取任何路由的_controller
值,而不仅仅是当前路由。
这可能吗,怎么可能?
PS:我发现我可以得到正在使用的 YAML 路由的路径,但重新解析它似乎不必要且繁重。
我真的很擅长回答我自己的问题。
要获取路由,请使用路由器上的getRouteCollection()
($this -> get('router') -> getRouteCollection()
控制器内部(,然后获取 RouteCollection 实例,您可以在该实例上all()
或get($name)
。
正如我上面的评论中所述Router::getRouteCollection
它真的很慢,不适合在生产代码中使用。
因此,如果您真的需要快速使用它,则必须破解它。请注意,这将是黑客攻击:
直接访问转储的路由数据
为了加快路由匹配,Symfony将所有静态路由编译成一个大的PHP类文件。此文件由 Symfony'Component'Routing'Generator'Dumper'PhpGeneratorDumper
生成,并声明一个将所有路由定义存储在名为 $declaredRoutes
的私有静态中的Symfony'Component'Routing'Generator'UrlGenerator
。
$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,并且可能会在未来的更新中中断(尽管在GitHub上最新的Symfony 4.1:PhpGeneratorDumper中它没有改变(。
但它相当短,足够快,可以用于生产。