与依赖注入有点混淆

时间:2013-06-06 17:16:08

标签: php symfony

我正在阅读http://symfony.com/doc/master/components/dependency_injection/introduction.html,然后我更加困惑自己,然后回答问题。我想在我的项目中使用DI,这样我就可以进行适当的测试以及DI带来的所有其他美妙的事情。

然而,我正在读这篇文章,直到http://symfony.com/doc/master/components/dependency_injection/introduction.html#avoiding-your-code-becoming-dependent-on-the-container

才有意义

您的代码如何不依赖于容器,这不是您访问容器的方式吗?

假设您有一个带有foo的类和一个带有bar的类

class Bar {
    public function bar() { return 'hello world'; }
}

class Foo {
   public function __construct(\Bar $bar) { $this->bar = $bar; };
   public function foo() { return $this->bar->bar(); }
}

所以你要通过

添加Bar对Foo的依赖
use Symfony\Component\DependencyInjection\ContainerBuilder;

$container = new ContainerBuilder();
$container->register('foo', 'Foo')->addArgument(new Reference('Bar'));

然后你想使用Foo(打印你好世界)你会做类似的事情

class Test {
    public function printHello($foo) {
        $foo->foo();
    }
}

$test = new Test();
$test->printHello($container->get('foo'));

或类似的东西。但该文件似乎说不使用$ container-> get?除非我错了。

1 个答案:

答案 0 :(得分:0)

我认为你误解了Avoiding Your Code Becoming Dependent on the Container。它不鼓励你做这样的事情:

class Foo
{

    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function foo()
    {
        $bar = $this->container->get('bar');
        $bar->bar();
    }
}

通过这种方式,您的代码将绑定到存在服务bar的服务容器。

所以,一般来说,只询问你需要什么(bar),而不要求整个宇宙(service_container)。

顺便说一下,如果不使用$container->get(),您仍然可以使用$bar = new Bar(); $foo = new Foo($bar);

之类的内容
相关问题