是否可以在编译过程中添加自定义路由?

时间:2013-09-04 15:31:03

标签: symfony bundle router

我准备外部包,我想在编译过程中添加一些路由。 路线将在主app/config/config.yml设置上创建。

我试图通过router ContainerBuilderCustomCompilerPass获取$definition = $container->getDefinition('router');

The service definition "router" does not exist

,但我得到{{1}}。

是否可以在编译过程中添加自定义路由?

2 个答案:

答案 0 :(得分:3)

无法在编译器传递中添加路由 为了动态加载路径(了解容器参数),我使用custom route loader

中给出的previous example
class MyLoader extends Loader
{
    protected $params;

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

    public function supports($resource, $type = null)
    {
        return $type === 'custom' && $this->params == 'YourLogic';
    }

    public function load($resource, $type = null)
    {
        // This method will only be called if it suits the parameters
        $routes   = new RouteCollection;
        $resource = '@AcmeFooBundle/Resources/config/dynamic_routing.yml';
        $type     = 'yaml';

        $routes->addCollection($this->import($resource, $type));

        return $routes;
    }
}

的routing.yml

_custom_routes:
    resource: .
    type:     custom

答案 1 :(得分:0)

router是别名,而不是服务。要从ContainerBuilder获取,请使用ContainerBuilder::getAlias。要获取服务ID,您需要将该对象强制转换为字符串:(string) $container->getAlias('router')。现在,您可以使用该ID获取服务:$container->getDefinition($container->getAlias('router'))。然后,您将获得可以修改的服务以添加路由。


顺便说一句,我不确定这是不是你想要的东西。如何使用CmfRoutingBundle。然后,您使用链路由器,因此您可以使用Symfony2路由器和DynamicRouter。 DynamicRouter可以与自定义路由提供程序一起使用,您可以在其中返回所需的路由(您可以从所需的每个资源中获取它们)。