meow / di
v0.1.0
2021-11-12 21:46 UTC
Requires
- php: 8.*
Requires (Dev)
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.6
This package is auto-updated.
Last update: 2024-09-13 04:49:26 UTC
README
PHP的依赖注入容器
命名空间: meow\di
安装
要安装此插件,请使用以下命令
composer require meow/di
用法
如何使用此容器的示例
创建新容器
要创建新容器,可以使用以下代码
$container = new ApplicationContainer();
注册服务
服务定义为数组 [接口 > 类]
,必须在解决你的类之前定义。
protected array $services = [ BaseServiceInterface::class => BaseService::class ]; // add services to container foreach ($this->services as $k => $v) { $container->set($k, $v); }
解决类
使用DI容器,您不需要在构造函数中创建新实例(如示例控制器 - 检查测试)。
class MainController { protected User $user; protected BaseServiceInterface $service; public function __construct(BaseServiceInterface $service, User $user) { $this->user = $user; $this->service = $service; } }
现在您可以使用容器解决控制器
/** @var MainController $controller */ $controller = $container->resolve(MainController::class);
许可证:MIT