Symfony 2:如何通过路由名称获取路由默认值?

时间:2012-02-16 17:39:54

标签: php symfony routes

是否可以按名称检索某条路线的信息,或获取所有路线的清单?

我需要能够在_controller中为任何路由获取defaults值,而不仅仅是当前路径。

这可能吗?如何?

P.S。:我发现我可以获得使用YAML路线的路径,但是重新分析它似乎是不必要和沉重的。

2 个答案:

答案 0 :(得分:6)

我很擅长回答自己的问题..

要在路由器(控制器内的getRouteCollection())上使用$this -> get('router') -> getRouteCollection()获取路由,然后获取RouteCollection实例,您可以all()get($name)

答案 1 :(得分:2)

正如我在上面的评论中所述,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中没有改变:PhpGeneratorDumper on GitHub)。

但它足够短而快,足以用于生产。

相关问题