我目前正在尝试找到一个可靠的解决方案来动态更改 Symfony2 服务的依赖项。详细说明:我有一个使用 HTTP 驱动程序与外部 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 可能会关闭、缓慢甚至损坏,而且我不想破坏构建。
目前我正在做这样的事情:
<?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?
最佳答案
我终于找到了一个对我来说看起来很可靠的解决方案。从 Symfony 2.4 开始,您可以使用表达式语法:Using the Expression Language
所以我以这种方式配置了我的服务。
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 条件服务声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25216089/