azexsoft / di
Azexsoft 依赖注入
v1.1.2
2022-05-07 19:54 UTC
Requires
- php: ^7.1|^8.0
- psr/container: ^1.0
Provides
- psr/container-implementation: 1.0.0
README
简单兼容PSR-11的基于自动装配的依赖注入容器和注入器,能够实例化和配置类以解决依赖。仅适用于类和接口。支持PHP 7.1+ 和 8.0+。
特性
- 兼容PSR-11。
- 检测循环引用。
- 支持类名、对象和闭包绑定。
- 支持服务提供者和延迟服务提供者。
- 注入器在构建类时为定义解决依赖,并调用依赖。
- 注入器支持带有方法参数和属性解析依赖的数组定义。
配置容器
只需创建包含绑定和服务提供者的数组实例。
// Bindings $bindings = [ FooInterface::class => Foo::class, // Classname binding Baz::class => new Baz(), // Object binding // Closure binding with DI resolving in Closure params Bar::class => fn(\Azexsoft\Di\Injector $injector) => $injector->build( Bar::class, [ 'config' => $params['barConfig'], 'someParameter' => 123 ] ), ]; // Service providers $providers = [ ApplicationServiceProvider::class, new FooServiceProvider(), ]; $container = new \Azexsoft\Di\Container($bindings, $providers);
此外,您还可以在容器配置后添加绑定和提供者。重新绑定后,旧实例将从容器中删除。
$foo = $container->get(FooInterface::class); // will be returned Foo $container->bind(FooInterface::class, OtherFoo::class); $otherFoo = $container->get(FooInterface::class); // will be returned OtherFoo
注入器构建器的数组定义。适用于bind()和provide()方法。
$container->bind(Abstract::class, [ '__class' => Concrete::class, // Concrete classname '__construct()' => [ 'simpleParam' => 123, 'otherSimpleParam' => $params['concreteSomeParam'], 'someObject' => new Definition(fn(Dependency $d) => $d->getSomeObject()), ], 'someMethod()' => [ 'methodParam' => $params['someMethodParam'], ], 'someProperty' => 321 ]);
而不是
$container->bind(Abstract::class, function(Injector $injector, Dependency $d) use ($params) { $concrete = $injector->build(Concrete::class, [ 'simpleParam' => 123, 'otherSimpleParam' => $params['concreteSomeParam'], 'someObject' => $d->getSomeObject(), ]); $concrete->someMethod($params['someMethodParam']); $concrete->someProperty = 321; return $concrete; });