Dependency Injection component依赖注入组件是Symfony程序中最重要的构成之一。本组件允许开发者以YAML、XML或PHP等格式配置服务,然后Symfony会根据定义创建实例。
服务通常要定义一个arguments
选项,罗列出要传入构造器的参数。如果程序中包含下面两个类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | namespace AppBundle\Service;
class Service1
{
}
namespace AppBundle\Service;
use AppBundle\Service\Service1;
class Service2
{
private $service1;
public function __construct(Service1 $service1)
{
$this->service1 = $service1;
}
} |
则所需之YAML配置文件会是这样:
1 2 3 4 5 6 7 8 | # app/config/services.yml
services:
service1:
class: AppBundle\Service\Service1
service2:
class: AppBundle\Service\Service2
arguments: ['@service1'] |
在Symfony 2.8中,得益于全新的service auto wiring(服务自动关联)功能,你可以跳过service1
的定义。这是因为服务容器能够内部检测到相应的构造器参数,为Service1
类创建一个私有服务,然后将其注入到service2
。
本功能默认是关闭的,这种行为被限制在特定情况下,即只当服务可以被清楚猜出时发生。你只需在发生关联的服务(定义)中,把新增的autowire
选项设为true
,剩下的事将交由服务容器完成。
下面演示如何把前例的服务配置通过自动关联来完成(service1
不需要显式配置,同时service2
不需要定义其参数):
1 2 3 4 5 | # app/config/services.yml
services:
service2:
class: AppBundle\Service\Service2
autowire: true |
服务自动关联是十余年前由Java框架Spring以其@Autowired
annotation始创的先驱,现今该功能(仅)适合简化原型程序的开发。