vakata / di
PHP DI
3.0.4
2024-02-20 12:11 UTC
Requires
- php: >=8.0.0
README
PHP 依赖注入 / 工厂。
安装
通过 Composer
$ composer require vakata/di
用法
namespace test; $di = new \vakata\di\Container(); interface I { } class A implements I {} class B { public function __construct(I $instance) { } } class C { public function __construct($firstParam, $secondParam) { } public function test($arg = 1) { return 1; } } // this will register class A, and an alias I for class A as the class implements that interface $di->register('\test\A'); $di->instance('\test\B'); // a B instance is created // when registering you can prevent interfaces being added as aliases as adding the aliases manually $di->register('\test\B', ['aliasedB']); // you can also pass default constructor params, which can be named $di->register('\test\C', null, ['secondParam' => 1, 2]); $di->instance('\test\C'); // this will invoke \test\C::__construct(2,1); $di->instance('\test\C', [2,4]); // this will invoke \test\C::__construct(2,4); // you can also register instances: $d = new D(); $di->register($d); // this is the same as \test\D // you can also make sure that there is only one instance of a given class $di->register('\some\class', ['aliases'], [/* default params */], true); // aside from register and instance there is an invoke method $di->invoke('\test\C', 'sum'); // returns 1 // you can also pass in arguments $di->invoke('\test\C', 'sum', [2]); // returns 2 // and even constructor parameters $di->invoke('\test\C', 'sum', [2], [5,6]); // invoke works with instances too $c1 = new C(); $di->invoke($c1, 'sum'); // returns 1
测试
$ composer test
贡献
有关详细信息,请参阅 CONTRIBUTING。
安全性
如果您发现任何与安全性相关的问题,请通过电子邮件 github@vakata.com 反馈,而不是使用问题跟踪器。
致谢
许可协议
MIT 许可协议 (MIT)。有关更多信息,请参阅 许可文件。