简体   繁体   English

Symfony 2依赖注入和自动装配

[英]Symfony 2 Dependency Injection & autowiring

I'm browsing the Symfony 2 docs related to Dependency Injection , and can't find a reference to autowiring. 我正在浏览与依赖注入相关的Symfony 2文档 ,但找不到自动装配的参考。 I found a bundle that offers some of this functionality , but it's still in beta and seems to be tied to annotations (correct me if I'm wrong). 我找到了一个提供此功能捆绑包 ,但它仍处于测试版状态,似乎与注释相关(如果我错了,请纠正我)。

What I'm looking for is an object (such as the service container), that could inject dependencies in my services, via setter injection. 我正在寻找的是一个对象(例如服务容器),它可以通过setter注入在我的服务中注入依赖项。

For example, I would define a Service: 例如,我将定义一个服务:

class Service {
    /**
     * @var \PDO
     */
    protected $pdo;

    /**
     * @param \PDO $pdo
     * @Inject
     */
    public function setPDO(\PDO $pdo) {
        $this->pdo = $pdo;
    }
}

And then, I could use this hypothetical service container to inject dependencies in the Service, even if this one has been created outside the container: 然后,我可以使用这个假设的服务容器在服务中注入依赖项,即使已在容器外创建了这个依赖项:

$service = new Service();
// ...

$container->inject($service);

Is there a DI container that could autowire dependencies this way? 是否有可以通过这种方式自动装配依赖关系的DI容器?

从Symfony 2.8开始,本机支持自动装配: https//github.com/symfony/symfony/pull/15613

还可以通过https://github.com/kutny/autowiring-bundle获得自动装配包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM