资讯专栏INFORMATION COLUMN

实现PHP的自动依赖注入容器 EasyDI容器

rickchen / 1347人阅读

摘要:年月日前言在看了一些容器实现代码后就手痒想要自己实现一个因此也就有了本文接下来的内容首先实现的容器需要具有以下几点特性符合标准实现基本的容器存储功能具有自动依赖解决能力本项目代码由托管可使用进行安装项目代码结构实现实现实现

[TOC]

Last-Modified: 2019年5月10日16:15:36

1. 前言

在看了一些容器实现代码后, 就手痒想要自己实现一个, 因此也就有了本文接下来的内容.

首先, 实现的容器需要具有以下几点特性:

符合PSR-11标准

实现基本的容器存储功能

具有自动依赖解决能力

本项目代码由GitHub托管

可使用Composer进行安装 composer require yjx/easy-di

2. 项目代码结构

</>复制代码

  1. |-src
  2. |-Exception
  3. |-InstantiateException.php (实现PsrContainerContainerExceptionInterface)
  4. |-InvalidArgumentException.php (实现PsrContainerContainerExceptionInterface)
  5. |-UnknownIdentifierException.php (实现PsrContainerNotFoundExceptionInterface)
  6. |-Container.php # 容器
  7. |-tests
  8. |-UnitTest
  9. |-ContainerTest.php
3. 容器完整代码

</>复制代码

  1. 代码版本 v1.0.1

</>复制代码

  1. raw(ContainerInterface::class, $this);
  2. $this->raw(self::class, $this);
  3. }
  4. /**
  5. * Finds an entry of the container by its identifier and returns it.
  6. *
  7. * @param string $id Identifier of the entry to look for.
  8. *
  9. * @throws NotFoundExceptionInterface No entry was found for **this** identifier.
  10. * @throws ContainerExceptionInterface Error while retrieving the entry.
  11. *
  12. * @return mixed Entry.
  13. */
  14. public function get($id, $parameters = [], $shared=false)
  15. {
  16. if (!$this->has($id)) {
  17. throw new UnknownIdentifierException($id);
  18. }
  19. if (array_key_exists($id, $this->raw)) {
  20. return $this->raw[$id];
  21. }
  22. if (array_key_exists($id, $this->instance)) {
  23. return $this->instance[$id];
  24. }
  25. $define = array_key_exists($id, $this->binding) ? $this->binding[$id] : $id;
  26. if ($define instanceof Closure) {
  27. $instance = $this->call($define, $parameters);
  28. } else {
  29. // string
  30. $class = $define;
  31. $params = (empty($this->params[$id]) ? [] : $this->params[$id]) + $parameters;
  32. // Case: "xxxxxx"=>"abc"
  33. if ($id !== $class && $this->has($class)) {
  34. $instance = $this->get($class, $params);
  35. } else {
  36. $dependencies = $this->getClassDependencies($class, $params);
  37. if (is_null($dependencies) || empty($dependencies)) {
  38. $instance = $this->getReflectionClass($class)->newInstanceWithoutConstructor();
  39. } else {
  40. $instance = $this->getReflectionClass($class)->newInstanceArgs($dependencies);
  41. }
  42. }
  43. }
  44. if ($shared || (isset($this->shared[$id]) && $this->shared[$id])) {
  45. $this->instance[$id] = $instance;
  46. }
  47. return $instance;
  48. }
  49. /**
  50. * @param callback $function
  51. * @param array $parameters
  52. * @return mixed
  53. * @throws InvalidArgumentException 传入错误的参数
  54. * @throws InstantiateException
  55. */
  56. public function call($function, $parameters=[], $shared=false)
  57. {
  58. //参考 http://php.net/manual/zh/function.call-user-func-array.php#121292 实现解析$function
  59. $class = null;
  60. $method = null;
  61. $object = null;
  62. // Case1: function() {}
  63. if ($function instanceof Closure) {
  64. $method = $function;
  65. } elseif (is_array($function) && count($function)==2) {
  66. // Case2: [$object, $methodName]
  67. if (is_object($function[0])) {
  68. $object = $function[0];
  69. $class = get_class($object);
  70. } elseif (is_string($function[0])) {
  71. // Case3: [$className, $staticMethodName]
  72. $class = $function[0];
  73. }
  74. if (is_string($function[1])) {
  75. $method = $function[1];
  76. }
  77. } elseif (is_string($function) && strpos($function, "::") !== false) {
  78. // Case4: "class::staticMethod"
  79. list($class, $method) = explode("::", $function);
  80. } elseif (is_scalar($function)) {
  81. // Case5: "functionName"
  82. $method = $function;
  83. } else {
  84. throw new InvalidArgumentException("Case not allowed! Invalid Data supplied!");
  85. }
  86. try {
  87. if (!is_null($class) && !is_null($method)) {
  88. $reflectionFunc = $this->getReflectionMethod($class, $method);
  89. } elseif (!is_null($method)) {
  90. $reflectionFunc = $this->getReflectionFunction($method);
  91. } else {
  92. throw new InvalidArgumentException("class:$class method:$method");
  93. }
  94. } catch (ReflectionException $e) {
  95. // var_dump($e->getTraceAsString());
  96. throw new InvalidArgumentException("class:$class method:$method", 0, $e);
  97. }
  98. $parameters = $this->getFuncDependencies($reflectionFunc, $parameters);
  99. if ($reflectionFunc instanceof ReflectionFunction) {
  100. return $reflectionFunc->invokeArgs($parameters);
  101. } elseif ($reflectionFunc->isStatic()) {
  102. return $reflectionFunc->invokeArgs(null, $parameters);
  103. } elseif (!empty($object)) {
  104. return $reflectionFunc->invokeArgs($object, $parameters);
  105. } elseif (!is_null($class) && $this->has($class)) {
  106. $object = $this->get($class, [], $shared);
  107. return $reflectionFunc->invokeArgs($object, $parameters);
  108. }
  109. throw new InvalidArgumentException("class:$class method:$method, unable to invoke.");
  110. }
  111. /**
  112. * @param $class
  113. * @param array $parameters
  114. * @throws ReflectionException
  115. */
  116. protected function getClassDependencies($class, $parameters=[])
  117. {
  118. // 获取类的反射类
  119. $reflectionClass = $this->getReflectionClass($class);
  120. if (!$reflectionClass->isInstantiable()) {
  121. throw new InstantiateException($class);
  122. }
  123. // 获取构造函数反射类
  124. $reflectionMethod = $reflectionClass->getConstructor();
  125. if (is_null($reflectionMethod)) {
  126. return null;
  127. }
  128. return $this->getFuncDependencies($reflectionMethod, $parameters, $class);
  129. }
  130. protected function getFuncDependencies(ReflectionFunctionAbstract $reflectionFunc, $parameters=[], $class="")
  131. {
  132. $params = [];
  133. // 获取构造函数参数的反射类
  134. $reflectionParameterArr = $reflectionFunc->getParameters();
  135. foreach ($reflectionParameterArr as $reflectionParameter) {
  136. $paramName = $reflectionParameter->getName();
  137. $paramPos = $reflectionParameter->getPosition();
  138. $paramClass = $reflectionParameter->getClass();
  139. $context = ["pos"=>$paramPos, "name"=>$paramName, "class"=>$paramClass, "from_class"=>$class];
  140. // 优先考虑 $parameters
  141. if (isset($parameters[$paramName]) || isset($parameters[$paramPos])) {
  142. $tmpParam = isset($parameters[$paramName]) ? $parameters[$paramName] : $parameters[$paramPos];
  143. if (gettype($tmpParam) == "object" && !is_a($tmpParam, $paramClass->getName())) {
  144. throw new InstantiateException($class."::".$reflectionFunc->getName(), $parameters + ["__context"=>$context, "tmpParam"=>get_class($tmpParam)]);
  145. }
  146. $params[] = $tmpParam;
  147. // $params[] = isset($parameters[$paramName]) ? $parameters[$paramName] : $parameters[$pos];
  148. } elseif (empty($paramClass)) {
  149. // 若参数不是class类型
  150. // 优先使用默认值, 只能用于判断用户定义的函数/方法, 对系统定义的函数/方法无效, 也同样无法获取默认值
  151. if ($reflectionParameter->isDefaultValueAvailable()) {
  152. $params[] = $reflectionParameter->getDefaultValue();
  153. } elseif ($reflectionFunc->isUserDefined()) {
  154. throw new InstantiateException("UserDefined. ".$class."::".$reflectionFunc->getName());
  155. } elseif ($reflectionParameter->isOptional()) {
  156. break;
  157. } else {
  158. throw new InstantiateException("SystemDefined. ".$class."::".$reflectionFunc->getName());
  159. }
  160. } else {
  161. // 参数是类类型, 优先考虑解析
  162. if ($this->has($paramClass->getName())) {
  163. $params[] = $this->get($paramClass->getName());
  164. } elseif ($reflectionParameter->allowsNull()) {
  165. $params[] = null;
  166. } else {
  167. throw new InstantiateException($class."::".$reflectionFunc->getName()." {$paramClass->getName()} ");
  168. }
  169. }
  170. }
  171. return $params;
  172. }
  173. protected function getReflectionClass($class, $ignoreException=false)
  174. {
  175. static $cache = [];
  176. if (array_key_exists($class, $cache)) {
  177. return $cache[$class];
  178. }
  179. try {
  180. $reflectionClass = new ReflectionClass($class);
  181. } catch (Exception $e) {
  182. if (!$ignoreException) {
  183. throw new InstantiateException($class, 0, $e);
  184. }
  185. $reflectionClass = null;
  186. }
  187. return $cache[$class] = $reflectionClass;
  188. }
  189. protected function getReflectionMethod($class, $name)
  190. {
  191. static $cache = [];
  192. if (is_object($class)) {
  193. $class = get_class($class);
  194. }
  195. if (array_key_exists($class, $cache) && array_key_exists($name, $cache[$class])) {
  196. return $cache[$class][$name];
  197. }
  198. $reflectionFunc = new ReflectionMethod($class, $name);
  199. return $cache[$class][$name] = $reflectionFunc;
  200. }
  201. protected function getReflectionFunction($name)
  202. {
  203. static $closureCache;
  204. static $cache = [];
  205. $isClosure = is_object($name) && $name instanceof Closure;
  206. $isString = is_string($name);
  207. if (!$isString && !$isClosure) {
  208. throw new InvalidArgumentException("$name can"t get reflection func.");
  209. }
  210. if ($isString && array_key_exists($name, $cache)) {
  211. return $cache[$name];
  212. }
  213. if ($isClosure) {
  214. if (is_null($closureCache)) {
  215. $closureCache = new SplObjectStorage();
  216. }
  217. if ($closureCache->contains($name)) {
  218. return $closureCache[$name];
  219. }
  220. }
  221. $reflectionFunc = new ReflectionFunction($name);
  222. if ($isString) {
  223. $cache[$name] = $reflectionFunc;
  224. }
  225. if ($isClosure) {
  226. $closureCache->attach($name, $reflectionFunc);
  227. }
  228. return $reflectionFunc;
  229. }
  230. /**
  231. * Returns true if the container can return an entry for the given identifier.
  232. * Returns false otherwise.
  233. *
  234. * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
  235. * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
  236. *
  237. * @param string $id Identifier of the entry to look for.
  238. *
  239. * @return bool
  240. */
  241. public function has($id)
  242. {
  243. $has = array_key_exists($id, $this->binding) || array_key_exists($id, $this->raw) || array_key_exists($id, $this->instance);
  244. if (!$has) {
  245. $reflectionClass = $this->getReflectionClass($id, true);
  246. if (!empty($reflectionClass)) {
  247. $has = true;
  248. }
  249. }
  250. return $has;
  251. }
  252. public function needResolve($id)
  253. {
  254. return !(array_key_exists($id, $this->raw) && (array_key_exists($id, $this->instance) && $this->shared[$id]));
  255. }
  256. public function keys()
  257. {
  258. return array_unique(array_merge(array_keys($this->raw), array_keys($this->binding), array_keys($this->instance)));
  259. }
  260. public function instanceKeys()
  261. {
  262. return array_unique(array_keys($this->instance));
  263. }
  264. public function unset($id)
  265. {
  266. unset($this->shared[$id], $this->binding[$id], $this->raw[$id], $this->instance[$id], $this->params[$id]);
  267. }
  268. public function singleton($id, $value, $params=[])
  269. {
  270. $this->set($id, $value, $params, true);
  271. }
  272. /**
  273. * 想好定义数组, 和定义普通项
  274. * @param $id
  275. * @param $value
  276. * @param bool $shared
  277. */
  278. public function set($id, $value, $params=[], $shared=false)
  279. {
  280. if (is_object($value) && !($value instanceof Closure)) {
  281. $this->raw($id, $value);
  282. return;
  283. } elseif ($value instanceof Closure) {
  284. // no content
  285. } elseif (is_array($value)) {
  286. $value = [
  287. "class" => $id,
  288. "params" => [],
  289. "shared" => $shared
  290. ] + $value;
  291. if (!isset($value["class"])) {
  292. $value["class"] = $id;
  293. }
  294. $params = $value["params"] + $params;
  295. $shared = $value["shared"];
  296. $value = $value["class"];
  297. } elseif (is_string($value)) {
  298. // no content
  299. }
  300. $this->binding[$id] = $value;
  301. $this->shared[$id] = $shared;
  302. $this->params[$id] = $params;
  303. }
  304. public function raw($id, $value)
  305. {
  306. $this->unset($id);
  307. $this->raw[$id] = $value;
  308. }
  309. public function batchRaw(array $data)
  310. {
  311. foreach ($data as $key=>$value) {
  312. $this->raw($key, $value);
  313. }
  314. }
  315. public function batchSet(array $data, $shared=false)
  316. {
  317. foreach ($data as $key=>$value) {
  318. $this->set($key, $value, $shared);
  319. }
  320. }
  321. }
3.1 容器主要提供方法

容器提供方法:

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对应条目

3.2 符合PSR-11标准

EasyDI(本容器)实现了 PsrContainerContainerInterface 接口, 提供 has($id)get($id, $params=[]) 两个方法用于判断及获取条目.

对于无法解析的条目识别符, 则会抛出异常(实现了 NotFoundExceptionInterface 接口).

3.3 容器的基本存储

容器可用于保存 不被解析的条目, 及自动解析的条目.

不被解析的条目
主要用于保存 配置参数, 已实例化对象, 不被解析的闭包

自动解析的条目
get(...) 时会被容器自动解析, 若是 闭包 则会自动调用, 若是 类名 则会实例化, 若是 别名 则会解析其对应的条目.

3.4 自动依赖解决

EasyDI 在调用 闭包 及 实例化 已经 调用函数/方法(call()) 时能够自动注入所需的依赖, 其中实现的原理是使用了PHP自带的反射API.

此处主要用到的反射API如下:

ReflectionClass

ReflectionFunction

ReflectionMethod

ReflectionParameter

3.4.1 解决类构造函数依赖

解析的一般步骤:

获取类的反射类 $reflectionClass = new ReflectionClass($className)

判断能够实例化 $reflectionClass->isInstantiable()

若能实例化, 则获取对应的构造函数的反射方法类 $reflectionMethod = $reflectionClass->getConstructor()

</>复制代码

  1. 3.1. 若返回null, 则表示无构造函数可直接跳到*步骤6*
  2. 3.2 若返回ReflectionMethod实例, 则开始解析其参数

获取构造函数所需的所有依赖参数类 $reflectionParameters = $reflectionMethod->getParameters

逐个解析依赖参数 $reflectionParameter

</>复制代码

  1. 5.1 获取参数对应名及位置 `$reflectionParameter->getName()`, `$reflectionParameter->getClass()`
  2. 5.2 获取参数对应类型 `$paramClass = $reflectionParameter->getClass()`
  3. 5.2.1 若本次解析手动注入了依赖参数, 则根据参数位置及参数名直接使用传入的依赖参数 Eg. `$container->get($xx, [1=>123, "e"=>new Exception()])`
  4. 5.2.2 若参数是标量类型, 若参数有默认值(`$reflectionParameter->isDefaultValueAvailable()`)则使用默认值, 否则抛出异常(无法处理该依赖)
  5. 5.2.3 若参数是 *class* 类型, 若容器可解析该类型, 则由容器自动实例化 `$this->get($paramClass->getName())`, 若无法解析但该参数允许null, 则传入null值, 否则抛出异常(无法处理来依赖)

若依赖参数为空则调用 $reflectionClass->newInstanceWithoutConstructor(), 否则调用 $reflectionClass->newInstanceArgs($dependencies); //$dependencies为步骤5中构造的依赖参数数组

</>复制代码

  1. 具体完整代码请参照容器类的 getClassDependencies(...) 方法.

3.4.2 解决 callable 的参数依赖

使用 call(...) 来调用 可调用 时, 自动解决依赖同样类似上述过程, 只是需要区分是 类函数, 类静态方法 还是 普通方法, 并相应的使用不同的反射类来解析,

</>复制代码

  1. 具体完整代码请参照容器类的 call(...) 方法

</>复制代码

  1. class UserManager
  2. {
  3. private $mailer;
  4. public function __construct(Mailer $mailer)
  5. {
  6. $this->mailer = $mailer;
  7. }
  8. public function register($email, $password)
  9. {
  10. // The user just registered, we create his account
  11. // ...
  12. // We send him an email to say hello!
  13. $this->mailer->mail($email, "Hello and welcome!");
  14. }
  15. public function quickSend(Mailer $mailer, $email, $password)
  16. {
  17. $mailer->mail($email, "Hello and welcome!");
  18. }
  19. }
  20. function testFunc(UserManager $manager)
  21. {
  22. return "test";
  23. }
  24. // 实例化容器
  25. $c = new EasyDIContainer();
  26. // 输出: "test"
  27. echo $c->call("testFunc")."
  28. ";
  29. // 输出: "test"
  30. echo $c->call(function (UserManager $tmp) {
  31. return "test";
  32. });
  33. // 自动实例化UserManager对象 [$className, $methodName]
  34. $c->call([UserManager::class, "register"], ["password"=>123, "email"=>"1@1.1"]);
  35. // 自动实例化UserManager对象 $methodFullName
  36. $c->call(UserManager::class."::"."register", ["password"=>123, "email"=>"1@1.1"]);
  37. // 调用类的静态方法 [$className, $staticMethodName]
  38. $c->call([UserManager::class, "quickSend"], ["password"=>123, "email"=>"1@1.1"]);
  39. // 使用字符串调用类的静态方法 $staticMethodFullName
  40. $c->call(UserManager::class."::"."quickSend", ["password"=>123, "email"=>"1@1.1"]);
  41. // [$obj, $methodName]
  42. $c->call([new UserManager(new Mailer()), "register"], ["password"=>123, "email"=>"1@1.1"]);
  43. // [$obj, $staticMethodName]
  44. $c->call([new UserManager(new Mailer()), "quickSend"], ["password"=>123, "email"=>"1@1.1"]);
4. 未完..不一定续

暂时写到此处.

后续项目最新代码直接在 GitHub 上维护, 该博文后续视评论需求来决定是否补充.

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/31438.html

相关文章

  • PHP IOC/DI 容器 - 依赖自动注入/依赖单例注入/依赖契约注入/参数关联传值

    摘要:标量参数关联传值依赖是自动解析注入的,剩余的标量参数则可以通过关联传值,这样比较灵活,没必要把默认值的参数放在函数参数最尾部。 更新:github(给个小星星呀) -- 2018-4-11:优化服务绑定方法 ::bind 的类型检查模式 借助 PHP 反射机制实现的一套 依赖自动解析注入 的 IOC/DI 容器,可以作为 Web MVC 框架 的应用容器 1、依赖的自动注入:你只需要...

    Paul_King 评论0 收藏0
  • 又一个强大PHP5.3依赖注入容器

    摘要:现在我们就可以在构造函数或者任何其他通过服务容器注入依赖项的地方使用类型提示注入接口创建一个新的类实例,此处将注入的实例。自动解析构造函数所需的依赖的服务容器实现了接口。 简单的服务容器 一个简单的 php 5.3 依赖注入容器。 项目地址:https://github.com/godruoyi/easy-container Why 目前比较流行的 PHP 容器: Pimple La...

    sf190404 评论0 收藏0
  • 【译文】PHP-DI和依赖注入最佳实践

    摘要:在构造函数中注入依赖性在中作为服务的控制器这是痛苦的,当你有个以上的依赖项,你的构造函数是行样板代码在属性中注入依赖性这是我们建议的解决方案。 PHP-DI是用PHP编写的、强大的和实用的、框架无关的依赖注入容器。这是一个关于如何使用PHP-DI和依赖注入的最佳实践指南。 文章来源于PHP-DI,作者:Matthieu Napoli和贡献者。PHP-DI是用PHP编写的、强大的和实用的...

    ivydom 评论0 收藏0
  • php实现依赖注入(DI)和控制反转(IOC)

    摘要:工厂模式,依赖转移当然,实现控制反转的方法有几种。其实我们稍微改造一下这个类,你就明白,工厂类的真正意义和价值了。虽然如此,工厂模式依旧十分优秀,并且适用于绝大多数情况。 此篇文章转载自laravel-china,chongyi的文章https://laravel-china.org/top...原文地址: http://www.insp.top/learn-lar... ,转载务必保...

    tomato 评论0 收藏0
  • 【modernPHP专题(3)】依赖注入与服务容器

    摘要:而依赖倒置原则的思想是,上层不应该依赖下层,应依赖接口。上面通过构造函数注入对象的方式,就是最简单的依赖注入当然注入不仅可以通过构造函数注入,也可以通过属性注入,上面你可以通过一个来动态为这个属性赋值。 依赖倒置和控制反转是一种编程思想,而依赖注入就是通过服务容器实现这种面向接口或者是面向抽象编程的思想 概念理解 依赖倒置原则 依赖倒置是一种软件设计思想,在传统软件中,上层代码依赖于下...

    terro 评论0 收藏0

发表评论

0条评论

rickchen

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<