简体   繁体   English

如何在Symfony2的自定义路由加载器中获取环境?

[英]How to get environment in custom route loader in Symfony2?

I've created a custom loader for my bundle with the purpose of loading different routes per environment. 我已经为我的捆绑包创建了一个自定义加载器,目的是为每个环境加载不同的路由。 My loader class looks like this: 我的加载程序类如下所示:

class ApiRouteLoader extends Loader
{
    public function load($resource, $type = null)
    {
        $collection = new RouteCollection();

        $resource = '@ApiBundle/Resources/config/routing.yml';
        $type = 'yaml';

        $importedRoutes = $this->import($resource, $type);

        $collection->addCollection($importedRoutes);

        return $collection;
    }

    public function supports($resource, $type = null)
    {
        return $type === 'extra';
    }
}

What I need to know is how could I get the environment name to use in the 'load' function? 我需要知道的是如何获取“加载”功能中使用的环境名称? I seem to unable to find a way to get the kernel (which would help). 我似乎无法找到一种获取内核的方法(这将有所帮助)。

Can anyone help? 有人可以帮忙吗? Thanks! 谢谢!

Injecting a parameter is a pretty basic operation. 注入参数是非常基本的操作。 You might want to take some time to research the service container. 您可能需要花一些时间来研究服务容器。 http://symfony.com/doc/current/book/service_container.html http://symfony.com/doc/current/book/service_container.html

In any event: 在任何情况下:

// services.yml
services:
    acme_demo.routing_loader:
        class: Acme\DemoBundle\Routing\ApiRouteLoader
        arguments: ['%kernel.environment%']
        tags:
            - { name: routing.loader }

class ApiRouteLoader extends Loader
{
    protected $env;

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

Just a quick update since somebody recently up voted this. 自从最近有人投票赞成以来,这只是一个快速更新。 For more recent versions of Symfony relying on environmental variables, use the following to inject the current env: 对于依赖于环境变量的最新版本的Symfony,请使用以下命令注入当前的env:

Acme\DemoBundle\Routing\ApiRouteLoader:
    $env:  '%env(APP_ENV)%'

You can inject the kernel.environment container parameter into your custom routing loader. 您可以将kernel.environment容器参数注入到您的自定义路由加载器中。

Btw, why do you create a routing loader that does nothing more than loading a route file from a specific path? 顺便说一句,为什么您要创建一个路由加载器,该加载器仅从特定路径加载路由文件? You can simple import that path into your routing.yml file: 您可以将该路径简单地导入到routing.yml文件中:

api_routes:
    resource: "@ApiBundle/Resources/config/routing.yml"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM