0

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!

1
  • When you say enviroment what do actually mean? Commented Oct 2, 2014 at 10:09

2 Answers 2

2

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)%'
Sign up to request clarification or add additional context in comments.

Comments

1

You can inject the kernel.environment container parameter into your custom routing loader.

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:

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

1 Comment

Hi, Wouter, thanks for the answer. Would you be so kind as to give me an example on how to inject the 'kernel.environment' into my loader? I am not adding the yml as a resource to the various routings defined on each environment as I am eventually going to apply some transformations and/or mix routes from different sources. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.