2

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

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

4

1 回答 1

2

You can dynamically create routes by creating your own Route Loader

First, declare the service

services.yml

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

Then, create the class

Acme\FooBundle\Loader\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;
    }
}

Then just add the importation into your routing

app/config/routing.yml

_custom_routes:
    resource: .
    type:     custom
于 2013-08-29T09:05:12.580 回答