borodulin / container
PSR 容器
dev-master
2020-05-18 10:43 UTC
Requires
- php: ^7.3
- borodulin/finder: ^1.0
- opis/closure: ^3.5
- psr/cache: ^1.0
- psr/container: ^1.0
- psr/simple-cache: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- phpstan/phpstan: ^0.12.23
- phpunit/phpcov: ^7.0
- phpunit/phpunit: ^9.1
This package is auto-updated.
Last update: 2024-09-18 20:18:48 UTC
README
特性
- PSR-11 全功能实现。
- 允许通过文件查找器和/或配置文件自动装配。
- 允许从其他容器中查找并解析依赖项。
- 允许通过参数包注入标量类型。
- 检测循环引用。
- 支持别名。
- 支持闭包。
- 支持 PSR-16 缓存。
使用容器
容器可以通过文件查找器初始化。
// autowire all classes in Samples directory $fileFinder = (new \Borodulin\Finder\ClassFinder()) ->addPath(__DIR__.'/../Samples'); // build container $container = (new \Borodulin\Container\ContainerBuilder()) ->setClassFinder($fileFinder) ->build();
容器可以通过配置文件初始化。
./config/definitions.php
:
<?php return [ 'test.bar' => Bar::class, 'test.foo' => function (Bar $bar) { return new Foo($bar); }, ];
// build container $container = (new \Borodulin\Container\ContainerBuilder()) ->setConfig(require(__DIR__ . '/config/definitions.php')) ->build();
容器构建完成后,可以通过 get()
获取对象
$object = $container->get('test.foo');
“用户不应将容器传递给对象,以便对象可以检索自己的依赖项。这样做的人正在将容器用作服务定位器。通常不鼓励使用服务定位器。”