在Symfony2中获取路由需求变量

Ben*_*Ben 2 yaml symfony

为了给我创建一个导航webinterface,我想从我的bundle的路由配置中获取一个变量.我在mybundle/Resources/config/routing.yml中定义了可用的页面.

mybundle_homepage:
  pattern:  /{_locale}/{branch}/{page}
  defaults: { _controller: mybundle:mycontroller:index, _locale: de, branch: x.x.x, page: start }
  requirements:
    _locale:  de|en
    page:     start|functions|events|constants|styleguide
Run Code Online (Sandbox Code Playgroud)

现在我看一下Symfony2 YAML Parser,我必须为它的静态方法解析提供一个文件路径:http://symfony.com/doc/2.0/reference/YAML.html

mycontroller.php

use Symfony\Component\Yaml\Yaml;

class mycontroller extends Controller
{
  public function indexAction($_locale, $branch, $page)
  {
    $routing = Yaml::parse('../Resources/config/routing.yml');
    var_dump($routing);
  }
}
Run Code Online (Sandbox Code Playgroud)

我以为我可以这样做,因为文件夹hirarchy看起来像那样:

  • mybundle
    • 调节器
      • mycontroller.php
    • Rescources
      • 配置
        • 使用routing.yml

但它不起作用.从路由文件中获取requirements.page数组的任何想法或其他方法?

问候,本

Ale*_*tis 6

您应该能够在识别DI容器的类中访问路由器服务.所以,你可以这样写:

$routes = $this->container->get('router')->getRouteCollection();

$route = $routes->get('my_route_name');
print_r($route->getRequirements());
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这不会使用任何缓存,因此路由器将在每次调用`getRouteCollection()时加载所有路由. (4认同)