PHP-DI是一个依赖注入容器,意味着实用、强大和框架无关。
PHP-DI使用PHP的Reflection类,这是非常标准的,Laravel、Zend Framework和许多其他容器也是同样做的。 性能方面,这样的信息被读取一次然后缓存,它没有影响。
PHP-DI有3种方法来定义在类中注入什么:
- 使用自动装配(autowiring)
- 使用注释(annotations)
- 使用PHP定义(PHP definitions)
每一个都是不同的和可选的。 以下是一个文件中的PHP定义的例子:
return [ 'api.url' => 'http://api.example.com', 'Webservice' => function (Container $c) { return new Webservice($c->get('api.url')); }, 'Controller' => DI\object() ->constructor(DI\get('Webservice')),];
但是我们不想在我们的应用程序中调用容器:它将我们的代码耦合到容器。 这被称为服务定位器反模式或依赖性提取而不是注入。
引用Symfony文档中所述:
You will need to get [an object] from the container at some point but this should be as few times as possible at the entry point to your application.
(你需要在某个点从容器中获取(get)一个对象,但在您应用程序的入口点次数应尽可能少。)
因此,PHP-DI与一些框架集成,这样您不必调用容器(依赖注入到控制器中):
- Symfony
- Silex
- Zend Framework 1
- Zend Framework 2
- Silly