phpsymfonysymfony-2.4

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!


Solution

  • 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

    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:

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