Download the PHP package yjx/easy-di without Composer
On this page you can find all versions of the php package yjx/easy-di. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Package easy-di
Short Description An easy dependencies inject container, which implements Psr-11.
License MIT
Informations about the package easy-di
EasyDI
EasyDI是一个具有自动依赖注入的小型容器, 遵循PSR-11.
具体详细介绍及讨论请参见blog
容器提供方法:
-
raw(string $id, mixed $value)
适用于保存参数,$value
可以是任何类型, 容器不会对其进行解析. -
set(string $id, \Closure|array|string $value, array $params=[], bool $shared=false)
定义服务 -
singleton(string $id, \Closure|array|string $value, array $params=[])
等同调用set($id, $value, $params, true)
-
has(string $id)
判断容器是否包含$id对应条目 -
get(string $id, array $params = [])
从容器中获取$id对应条目, 可选参数$params可优先参与到条目实例化过程中的依赖注入 -
call(callable $function, array $params=[])
利用容器来调用callable, 由容器自动注入依赖. unset(string $id)
从容器中移除$id对应条目
安装 Installation
Install EasyDi with Composer
composer require yjx/easy-di
基础使用 Basic Usage
容器的实例化
EasyDI容器管理两种类型的数据: 服务 和 参数(raw)
定义服务和参数
闭包中的参数
$c
由于使用了类型指示, 因此EasyDI会自动完成依赖注入(将它自身注入).
自动依赖解决
示例1
直接拿PHP-DI官方演示代码
示例2
示例3 call()
php class UserManager { private $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
public function register($email, $password)
{
// The user just registered, we create his account
// ...
// We send him an email to say hello!
$this->mailer->mail($email, 'Hello and welcome!');
}
public function quickSend(Mailer $mailer, $email, $password)
{
$mailer->mail($email, 'Hello and welcome!');
}
}
function testFunc(UserManager $manager) { return "test"; }
// 实例化容器 $c = new EasyDI\Container();
// 输出: 'test' echo $c->call('testFunc')."\n";
// 输出: 'test' echo $c->call(function (UserManager $tmp) { return 'test'; });
// 自动实例化UserManager对象 [$className, $methodName] $c->call([UserManager::class, 'register'], ['password'=>123, 'email'=>'[email protected]']);
// 自动实例化UserManager对象 $methodFullName $c->call(UserManager::class.'::'.'register', ['password'=>123, 'email'=>'[email protected]']);
// 调用类的静态方法 [$className, $staticMethodName] $c->call([UserManager::class, 'quickSend'], ['password'=>123, 'email'=>'[email protected]']);
// 使用字符串调用类的静态方法 $staticMethodFullName $c->call(UserManager::class.'::'.'quickSend', ['password'=>123, 'email'=>'[email protected]']);
// [$obj, $methodName] $c->call([new UserManager(new Mailer()), 'register'], ['password'=>123, 'email'=>'[email protected]']);
// [$obj, $staticMethodName] $c->call([new UserManager(new Mailer()), 'quickSend'], ['password'=>123, 'email'=>'[email protected]']);