【发布时间】:2014-07-14 11:55:42
【问题描述】:
我正在尝试使用 Symfony 依赖注入组件来使我的 PHP 类更易于单元测试。 但是,当我想要的类具有在运行时确定的构造函数参数时,我会陷入困境。必须使用参数实例化该类才有意义。所以我不想使用setter注入。我有一种感觉,在这种情况下我将无法使用依赖注入,需要重新组织我尝试这样做的方式,但我不确定我需要做什么......
我读到如果我有运行时参数,我应该使用抽象工厂,但是我的类也会有 $service 参数,它不是运行时参数,我想注入它,以便在运行测试时,我可以注入模拟服务。
如果抽象工厂是要走的路,我想知道如何将抽象工厂与 DI 一起使用,以便注入我的服务。
如果不是抽象工厂,我还有什么其他选择?
class Foo
{
public function myMethod()
{
$container = new ContainerBuilder();
$loader = new PhpFileLoader($container, new FileLocator(__DIR__));
$loader->load('services.php'); //Load the config
$container->compile();
//I don't know how to get a Bar because it has other runtime arguments.
$bar = $container->get('bar');
//...
}
}
class Bar
{
private $service;
public function __construct($userId, $date, $service)
{
$this->service = $service
//...
}
}
service.php(DI 容器配置):
$container->register('dao', 'Dao');
$container->register('service', 'Service')
->addArgument(new Reference('dao'));
$container->register('bar', 'Bar')
->addArgument(new Reference('service'));
【问题讨论】:
标签: php symfony dependency-injection