esase / tiny-service-manager
服务管理器是一个服务/对象定位器,负责检索其他对象
v1.0.3
2020-08-15 12:23 UTC
Requires
- php: ^7.4 || ^8.0
- psr/container: ^1.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.2
- phpunit/phpunit: ^9.0 || ^10.0
This package is auto-updated.
Last update: 2024-09-07 17:40:07 UTC
README
小型/服务管理器 - 它是 DI (依赖注入) 容器的一个简单实现,拥有清晰易懂的 API。(没有任何额外依赖,并且非常小巧)。
DI 容器
是任何现代 框架
或 CMS
的必要部分。换句话说,它是网络应用中最重要的一部分,为用户提供任何类型的服务(控制器
、服务
、工具
等)。
此外,它遵循 SOLID 原则之一(依赖注入或依赖倒置)。这意味着您不应该在对象中直接创建对象,因为这会给单元测试和维护嵌入式类带来困难。让我们看看几个示例
错误的做法
<?php class A { private B $embedded; public function __construct() { // Issues: // 1. we cannot test it because we cannot mimic it // 2. If we decide to use another implementation we will have to find and replace all its references $this->embedded = new B(); } }
最佳方式 - 是在 构造函数
或 设置器
(如果依赖项是可选的)中注入任何依赖项。
<?php class A { private B $embedded; public function __construct(B $embedded) { $this->embedded = $embedded; } }
服务管理器 动作
use Tiny\ServiceManager\ServiceManager; // The Service Manager is a service/object locator, tasked with retrieving other objects. $serviceManager = new ServiceManager([ B::class => function(ServiceManager $serviceManager) { return new B(); }, A::class => function(ServiceManager $serviceManager) { return new A($serviceManager->get(B::class)); } ]); // now whenever we get an instance of "A" class we get it with injected instance of "B" class $serviceA = $serviceManager->get(A::class);
现在我们可以轻松地测试 A
类,通过注入 B
的模拟版本。
$serviceA = new A(new MockedB());
有关更多详细信息,请参阅下面的文档链接。
安装
运行以下命令以安装此库
$ composer require esase/tiny-service-manager
文档
https://tiny-docs.readthedocs.io/en/latest/tiny-service-manager/docs/index.html