5

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

我试图routerContainerBuilder我的CustomCompilerPass通过:

$definition = $container->getDefinition('router');

,但我得到了The service definition "router" does not exist

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

4

2 回答 2

3

无法在编译器通道中添加路由。
为了动态加载路由(知道容器参数),我将使用我之前示例中给出的自定义路由加载器

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
于 2013-09-06T07:26:36.297 回答
0

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


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

于 2013-09-04T20:12:22.500 回答