encorephp 容器
具有服务提供者和代理的依赖注入容器。
dev-master / 0.1.x-dev
2015-03-09 22:54 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: 4.3.*
- scrutinizer/ocular: ~1.1
Suggests
- encorephp/events: Allows registration of service providers when events are fired
This package is not auto-updated.
Last update: 2024-09-14 15:12:47 UTC
README
EncorePHP 容器库为您的应用程序提供了一个快速且强大的依赖注入容器。
除了依赖注入容器之外,我们还允许使用服务提供者和代理。
安装
通过 Composer
$ composer require encorephp/container
使用方法
获取容器对象
require 'vendor/autoload.php'; $container = new Encore\Container\Container;
将具体类绑定到接口
$container->bind('\Foo\Bar\BazInterface', '\Foo\Bar\Baz');
自动依赖解析
容器能够通过检查对象构造函数上的类型提示递归解析对象及其依赖关系。
namespace Foo\Bar; class Baz { public function __construct(Qux $qux, Corge $corge) { $this->qux = $qux; $this->corge = $corge; } public function setQuux(Quux $quux) { $this->quux = $quux; } } $container->resolve('\Foo\Bar\Baz');
定义参数
或者,您可以在实例化类时指定要注入的内容。
定义构造函数参数
$container->bind('\Foo\Bar\Baz')->addArgs(array('\Foo\Bar\Quux', '\Foo\Bar\Corge')); $container->resolve('\Foo\Bar\Baz');
定义带有参数的方法
$container->bind('\Foo\Bar\Baz')->withMethod('setQuux', array('\Foo\Bar\Quux')); $container->resolve('\Foo\Bar\Baz');
解析继承的依赖
容器的一个出色功能是能够解析继承类和接口的依赖关系。例如,您可以将一个接口绑定到容器中,该接口需要通过方法注入依赖,而实现该接口的所有类也将自动注入该依赖。
$container->bind('\Foo\Bar\BazInterface')->withMethod('setQuux', ['\Foo\Bar\Quux']); $container->bind('\Foo\Bar\Baz'); $container->resolve('\Foo\Bar\Baz');
子容器和范围解析
容器的另一个出色功能是能够为其提供子容器,其解析范围与其父容器分开。如果您在一个容器中将具体类绑定到接口,您可以在子容器中重新绑定它,而不用担心会覆盖父容器中的原始绑定。
创建子容器
有两种创建子容器的方法。
$child = $continer->createChild(); // OR $child = new Container($container);
使用子容器
使用子容器的主要优点是特定范围的解析。
$container->bind('FooInterface', 'Foo'); // Assuming class Bar has a FooInterface dependency. // This would use the Foo implementation. $bar = $container->resolve('Bar'); // ... $child = $container->createChild(); $child->bind('FooInterface', 'Baz'); // And this would use the Baz implementation. $bar = $child->resolve('Bar');
测试
$ phpunit
贡献
有关详细信息,请参阅 CONTRIBUTING。
安全
如果您发现任何与安全相关的问题,请通过电子邮件发送到 chris@chrisnharvey.com,而不是使用问题跟踪器。
鸣谢
EncorePHP 容器基于已废弃的 league/di 包。
许可证
MIT 许可证 (MIT)。请参阅 许可证文件 获取更多信息。