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

问题描述 投票:0回答:3

是否可以通过名称检索有关特定路线的信息,或获取所有路线的列表?

我需要能够获取任何路线的

_controller
中的
defaults
值,而不仅仅是当前路线。

这可能吗?如何实现?

P.S.:我发现我可以获得正在使用的 YAML 路由的路径,但重新解析它似乎没有必要且繁重。

php symfony routes
3个回答
7
投票

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

要获取路由,请在路由器上使用

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


4
投票

正如我上面的评论所述,

Router::getRouteCollection
真的很慢,不适合在生产代码中使用。

因此,如果你真的需要快速使用它,你就必须想办法解决它。请注意,这将是黑客行为


直接访问转储的路线数据

为了加快路由匹配速度,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)。

但它相当短且快,足以用于生产。


0
投票

2024 年,

$this->get('route')
已弃用(并消失)

因此,将路由器注入您的控制器

use Symfony\Component\Routing\RouterInterface;
//...
class MyController extends AbstractController
   private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

并在您的方法中,按照上面 Tony Bogdanov 的描述访问它:

dump($this->router->getRouteCollection()->get('home'));
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.