Symfony2条件服务声明 [英] Symfony2 conditional service declaration
问题描述
我目前正试图找到一个可靠的解决方案来动态更改Symfony2服务的依赖关系.详细说明:我有一个使用HTTP驱动程序与外部API进行通信的服务.
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);
}
}
在CI上运行Behat测试时,我想使用httpMockDriver代替真正的驱动程序,因为外部API可能会关闭,运行缓慢甚至中断,并且我不想中断构建.
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');
}
}
}
这暂时有效,但肯定会中断.因此,有没有更优雅/更可靠的方法来动态更改HTTPDriver?
This works for now, but will break for sure. So, is there a more elegant/solid way to change the HTTPDriver dynamically?
推荐答案
我终于找到了对我来说很可靠的解决方案.从Symfony 2.4开始,您可以使用表达式语法:使用表达语言
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)"
这对我有用.
这篇关于Symfony2条件服务声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!