E
E
Egor2019-11-04 00:24:30
symfony
Egor, 2019-11-04 00:24:30

How to create a service in symfony, whose dependency is determined by the environment?

When executing unit tests (env=test), I would like to get a tested service from the service container, which was "cooked" with a "fake" dependency. Which particular class to use as a dependency should be determined depending on the env.
For example:

MyService 
{
  private $dependency;

  public function __constructor(DependencyInterface $dependency)
  {
    $this->dependency = $dependency;
  }

   public function getDependency(): DependencyInterface
   {
      return $this->dependency;
   }
}

DependencyInterface has 2 concrete classes:
RealDependency implement DependencyInterface{}
FakeDependency implement DependencyInterface{}

In the test, I would like to get FakeDependency, and in other environments - RealDependency:
MyServiceTest extends KernelTestCase
{
  public function testAction()
  {
    $kernel = self::bootKernel();
    $service = $kernel->getContainer()->get('app.my_service');

    $this->assertInstanceOf(FakeDependency::class, $service->getDependency());
   }
}

Is there such a possibility?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BoShurik, 2019-11-04
@egormmm

If the dependency is on APP_ENV, then it's easier like this

# config/services.yaml
services:
    DependencyInterface: '@RealDependency'

# config/services_test.yaml
services:
    DependencyInterface: '@FakeDependency'

If you need a dependency on some other environment variable, then you need to use the Maxim Fedorov option , because the container is compiled and at the stage of compilation the value from the environment variables is unknown

A
Alexey Skobkin, 2019-11-04
@skobkin

You can use expressions: https://symfony.com/doc/current/service_container/...
Or you can see how Symfony services are substituted depending on the environment (EventDispatcher, container, etc).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question