Autowiring (自动关联)使你能够在容器中以“最小化配置”来注册服务。它基于构造器的typehints(类型提示)自动解析出所依赖的服务,因此极大的减少了定义服务时所需的配置代码。

默认时,自动关联子系统仅针对服务的构造器中的依赖进行注入。然而,就算构造器注入是首选,有些时候通过方法完成注入更加方便(通常是用一个 setter 方法)。

这就是为何在Symfony 3.3中,自动关联子系统允许使用setter进行配置,这得益于被 autowiring 所支持的全新选项值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
services:
    app.manager.user:
        class: AppBundle\Manager\UserManager
        # to maintain backwards compatibility this value is
        # automatically transformed into "autowire: ['__construct']"
        # 因为要向下兼容,此处的值将被自动转换为 "autowire: ['__construct']"
        autowire: true
 
        # autowire the constructor and all the setters
        # 自动关联构造器和全部setter
        autowire: ['__construct', 'set*']
 
        # autowire only the foo() and bar() methods
        # 仅自动关联 foot() 和 bar() 方法
        autowire: ['foo', 'bar']