在Symfony 2.3中根据容器参数启用路由

时间:2013-08-29 08:38:29

标签: symfony

我创建了一个包含自己的routing.yml的包。 我只想在服务容器中设置某个参数时,我想导入它们,而不是简单地在我的应用程序的主要routing.yml中导入这些路由。 这样我就可以根据捆绑配置启用或禁用路由。有没有办法做到这一点,除了创建一个新的环境?

我想这样做的原因是因为我需要一些特殊压力测试设置的路由,这些设置永远不应该在其他部署中启用。

1 个答案:

答案 0 :(得分:2)

您可以通过创建自己的Route Loader

来动态创建路线

首先,声明服务

services.yml

services:
    acme_foo.route_loader:
        class: Acme\FooBundle\Loader\MyLoader
        arguments:
            - %my.parameter%
        tags:
            - { name: routing.loader }

然后,创建类

的Acme \ FooBundle \装载机\ MyLoader

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Config\Loader\Loader;

class MyLoader extends Loader
{
    protected $params;

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

    public function supports($resource, $type = null)
    {
        return $type === 'custom' && $this->param == '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/custom_routing.yml';
        $type     = 'yaml';

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

        return $routes;
    }
}

然后只需将导入添加到路由

应用/配置/ routing.yml中

_custom_routes:
    resource: .
    type:     custom