Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 conditional service declaration

I'm currently trying to find a solid solution to change the dependencies of a Symfony2 service dynamically. In detail: I have a Services which uses a HTTP-Driver to communicate with an external API.

class myAwesomeService
{
    private $httpDriver;

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

    public function transmitData($data)
    {
        $this->httpDriver->dispatch($data);
    } 
}

While running the Behat tests on the CI, I'd like to use a httpMockDriver instead of the real driver because the external API might be down, slow or even broken and I don't want to break the build.

At the moment I'm doing something like this:

<?php
namespace MyAwesome\TestBundle\DependencyInjection;

class MyAwesomeTestExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new       
                     FileLocator(__DIR__.'/../Resources/config'));
        $environment = //get environment
        if ($environment == 'test') {
            $loader->load('services_mock.yml');         
        } else {
            $loader->load('services.yml');          
        }
    }
}

This works for now, but will break for sure. So, is there a more elegant/solid way to change the HTTPDriver dynamically?

like image 890
sl0815 Avatar asked Aug 09 '14 07:08

sl0815


1 Answers

I finally found a solution that looks solid to me. As of Symfony 2.4 you can use the expression syntax: Using the Expression Language

So I configured my service this way.

service.yml
parameters:
  httpDriver.class:       HTTP\Driver\Driver
  httpMockDriver.class:   HTTP\Driver\MockDriver
  myAwesomeService.class: My\Awesome\Service
service:
  myAwesomeService:
    class:        "%myAwesomeService.class%"
    arguments:    
      - "@=service('service_container').get('kernel.environment') == 'test'? service('httpMockDriver) : service('httpDriver)"

This works for me.

like image 61
sl0815 Avatar answered Nov 08 '22 07:11

sl0815