alanvdb / dependency-container
基本的PSR-11依赖容器
Requires
- psr/container: ^2.0
Requires (Dev)
- phpunit/phpunit: ^11.3
This package is auto-updated.
Last update: 2024-09-13 13:58:25 UTC
README
PHP PSR-11 依赖注入系统
概述
本项目为PHP提供了一个轻量级的依赖注入系统。它包括以下主要组件:
LazyContainer
:一个延迟实例化服务的容器。IterableLazyContainer
:扩展了LazyContainer
并实现了Iterator
接口。ContainerFactory
:用于创建LazyContainer
和IterableLazyContainer
实例的工厂。
此库完全兼容PSR-11标准,该标准定义了依赖注入容器的通用接口。这确保了您的依赖注入容器可以与其他符合PSR-11标准的库互操作。
安装
要安装dependency-container,您可以使用Composer
composer require alanvdb/dependency-container
用法
LazyContainer
LazyContainer
类允许您通过一个仅在请求服务时调用的可调用对象注册服务。这提供了服务的延迟实例化,可以通过延迟服务的创建直到实际需要它们来提高性能。
示例
use AlanVdb\Dependency\LazyContainer; $container = new LazyContainer(); $container->add('service1', function() { return new Service1(); }); if ($container->has('service1')) { $service1 = $container->get('service1'); }
IterableLazyContainer
IterableLazyContainer
扩展了LazyContainer
并实现了Iterator
接口,允许您遍历已注册的服务。
示例
use AlanVdb\Dependency\IterableLazyContainer; $container = new IterableLazyContainer(); $container->add('service1', function() { return new Service1(); }); $container->add('service2', function() { return new Service2(); }); foreach ($container as $serviceId => $service) { // Process each service }
ContainerFactory
ContainerFactory
类提供了创建LazyContainer
和IterableLazyContainer
实例的方法。
示例
use AlanVdb\Dependency\Factory\ContainerFactory; $factory = new ContainerFactory(); $lazyContainer = $factory->createLazyContainer(); $iterableLazyContainer = $factory->createIterableLazyContainer();
PSR-11兼容性
本项目遵循PSR-11 容器接口,确保LazyContainer
和IterableLazyContainer
类符合标准。这允许与其他支持PSR-11的库和框架无缝集成。
关键的PSR-11方法
LazyContainer
和IterableLazyContainer
这些类实现了以下PSR-11方法:
get(string $id)
:通过其标识符从容器中检索条目。- 如果找不到标识符,则抛出一个实现
Psr\Container\NotFoundExceptionInterface
的异常。
- 如果找不到标识符,则抛出一个实现
has(string $id): bool
:如果容器可以返回给定标识符的条目,则返回true。
遵循PSR-11,这些容器可以在任何需要PSR-11兼容容器的地方使用。
API文档
LazyContainer
方法
-
add(string $id, callable $generator)
:向容器中添加一个新的服务。string $id
:服务标识符。callable $generator
:一个返回服务实例的可调用对象。
-
get(string $id)
:从容器中检索服务。string $id
:服务标识符。- 返回服务实例。
- 如果找不到服务标识符,则抛出
IdNotFoundException
。
-
has(string $id): bool
:检查容器中是否存在服务标识符。string $id
:服务标识符。- 如果服务存在,则返回
true
,否则返回false
。
IterableLazyContainer
IterableLazyContainer
继承了从LazyContainer
继承的所有方法,并实现了从Iterator
接口的额外方法
current()
:返回当前元素。key()
:返回当前元素的键。next()
:向前移动到下一个元素。rewind()
:回滚到第一个元素。valid()
:检查当前位置是否有效。
ContainerFactory
方法
createLazyContainer(): LazyContainerInterface
:创建一个新的LazyContainer
实例。createIterableLazyContainer(): LazyContainerInterface & Iterator
:创建一个新的IterableLazyContainer
实例。
测试
要运行测试,请使用以下命令
vendor/bin/phpunit
测试位于tests
目录,覆盖了LazyContainer
、IterableLazyContainer
和ContainerFactory
的功能。
许可证
本项目采用MIT许可证。有关详细信息,请参阅LICENSE文件。