EasySwoole实现了简单版的IOC,使用 IOC 容器可以很方便的存储/获取资源,实现解耦。
看看我的代码实现
1. 创建Di绑定容器的服务提供者 \App\Provide\DiProvide.php
<?php
namespace App\Provide;
use EasySwoole\Component\Di;
class DiProvide
{
/**
* 将对象 注册到ioc容器
*/
public static function injectIoc(){
// 注入绑定 接口名称与接口实现的类
Di::getInstance()->set(
\App\Services\Contract\TestServicesContract::class,
\App\Services\TestServices::class
);
// 当业务比较简单的时候,没有写接口 也可以 注入 类名称与之到对应的类
Di::getInstance()->set(
\App\Services\TestServices::class,
\App\Services\TestServices::class
);
// todo ... 写其他类的注入
}
/**
* 获取Ioc容器中的对象
* @param $className
* @return null
* @throws \Throwable
*/
public static function getIoc($className){
return Di::getInstance()->get($className);
}
}
- 在框架全局事件类 EasySwooleEvent.php 中 initialize() 方法注册服务提供者
\App\Provide\DiProvide::injectIoc();
3。在业务代码中使用,通过 Ioc容器获取对象实例
$testServices = \EasySwoole\Component\Di::getInstance()->get(\App\Services\Contract\TestServicesContract::class);
# 或者
$testServices = \EasySwoole\Component\Di::getInstance()->get(\App\Services\TestServices::class);
echo $testServices->test();
网友评论