igniphp / container
PSR-11 兼容的依赖容器
1.1.0
2018-03-20 16:57 UTC
Requires
- php: ^7.1.0
- psr/container: ~1.0
Requires (Dev)
- mockery/mockery: ^0.9.4
- phpunit/phpunit: ~5.7
This package is not auto-updated.
Last update: 2024-09-19 11:26:26 UTC
README
Igni 容器
MIT 许可证下许可。
Igni 容器是一个符合 psr-container
标准的轻量级服务定位器模式实现。
功能列表
- 简单使用 如果您熟悉
psr-container
,基本使用无需学习曲线 - 上下文感知 您可以为特定的用例定义服务的自定义实例。
- 自动绑定 所需的依赖自动注入到您的服务中
安装
composer install igniphp/container
基本使用
<?php $serviceLocator = new Igni\Container\ServiceLocator(); $serviceLocator->set('my_awesome_service', new stdClass()); $myService = $serviceLocator->get('my_awesome_service'); var_dump($myService === $serviceLocator->get('my_awesome_service')); // returns true
注册共享服务
共享服务是仅实例化一次的服务,其引用保存在注册表中,因此每次从容器请求服务时都会返回相同的实例。
<?php use Igni\Container\ServiceLocator; class Service { public $a; public function __construct(int $a = 1) { $this->a = $a; } } $serviceLocator = new ServiceLocator(); $serviceLocator->share(Service::class, function() { return new Service(2); }); var_dump($serviceLocator->get(Service::class)->a === 2); //true var_dump($serviceLocator->get(Service::class) === $serviceLocator->get(Service::class)); // true
分块服务
分块服务是在每次容器被请求服务时实例化的。
<?php use Igni\Container\ServiceLocator; class Service { public $a; public function __construct(int $a = 1) { $this->a = $a; } } $serviceLocator = new ServiceLocator(); $serviceLocator->factory(Service::class, function() { return new Service(2); }); var_dump($serviceLocator->get(Service::class)->a === 2); //true var_dump($serviceLocator->get(Service::class) === $serviceLocator->get(Service::class)); // false
自动绑定
自动绑定允许您简单地传递完全限定的类名以及该类的所有类型提示参数,这些参数将由容器自动解决。
<?php use Igni\Container\ServiceLocator; class A { } class Service { public $a; public $number; public function __construct(int $number = 7, A $a) { $this->number = $number; $this->a = $a; } } $serviceLocator = new ServiceLocator(); $serviceLocator->share(A::class); $serviceLocator->share(Service::class); var_dump($serviceLocator->get(Service::class)->a instanceof A);// true
这就全部了!