2012-02-16 84 views
2

是否有可能通過名稱檢索某條路線的信息,或獲取所有路線的列表?Symfony 2:如何通過路由名稱獲取路由默認值?

我需要能夠爲defaults獲取_controller的值,而不僅僅是當前值。

這是可能的和如何?

P.S .:我發現我可以得到正在使用的路由YAML的路徑,但重新分析似乎沒有必要和沉重。

回答

5

我在回答我自己的問題真的很好..

要獲得路由路由器上使用getRouteCollection()$this -> get('router') -> getRouteCollection()控制器內),那麼你得到RouteCollection實例可以在其上all()get($name)

+4

請記住,getRouteCollection不使用任何緩存值,因爲它的目的是重建緩存。所以稱它是非常不鼓勵的。它不適合在生產代碼中使用,並且對性能有很高的影響(請參閱:[關於YML路由加載程序未在運行時緩存的討論](https://github.com/symfony/symfony/issues/7368#issuecomment-15146130 ))。 – flu 2015-01-26 15:49:47

+0

...我真的很擅長找到自己的答案... – flu 2017-07-06 08:31:53

0

正如我在上面的評論中所述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(); 
// [...] 

所以要訪問它的requirem經濟需求,需要使用:

$routeRequirements = $dumpedRoutes['my_route'][2]; 

底線

我已經通過了Symfony的手冊,源代碼,論壇,計算器等等看了,但還是沒能找到一個更好的做法。

這是殘酷的,忽略了API,並可能在未來的更新中破解(雖然它在最近的Symfony 3.4中沒有變化:​​)。

但它相當短而且足夠快,可用於生產。