phespro / container
为PHP设计的超级简单的依赖注入容器
1.2.4
2023-11-01 19:37 UTC
Requires
- php: ^8.2
- psr/container: ^2.0
Requires (Dev)
- infection/infection: ^0.27
- phpunit/phpunit: ^10.3
README
phespro/container
为PHP设计的超级简单的依赖注入容器。
- 仅121行代码
- 无需缓存
- 包含标签和装饰
- 100%代码覆盖率 & 100%突变覆盖率
- 实现PSR-11
用法
安装它
composer require phespro/container
创建它
<?php
require __DIR__ . '/vendor/autoload.php';
$container = new Container;
使用它!!!
添加服务
$container->add('some_id', fn(Container $c) => new MyService); // register singleton
$container->addFactory('other_id', fn(Container $c) => new OtherService); // register factory
$container->add('tagged_service', fn(Container $c) => new TaggedService, ['console_command']);
获取服务
$container->has('some_id'); // does the service exist?
$container->get('some_id'); // get the service
$container->getByTag('console_command'); // get all services, tagged with 'console_command'
装饰服务
你可以装饰(或覆盖)服务
$container->decorate('some_id', fn(Container $c, callable $prev) => new Decorator($prev());
// or decorate it with factory
$container->decorateWithFactory('some_id', fn(Container $c, callable $prev) => new Decorator($prev()));