簡體   English   中英

Symfony 2:如何通過路由名稱獲取路由默認值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM