Container.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace think;
  13. use ArrayAccess;
  14. use ArrayIterator;
  15. use Closure;
  16. use Countable;
  17. use InvalidArgumentException;
  18. use IteratorAggregate;
  19. use Psr\Container\ContainerInterface;
  20. use ReflectionClass;
  21. use ReflectionException;
  22. use ReflectionFunction;
  23. use ReflectionFunctionAbstract;
  24. use ReflectionMethod;
  25. use think\exception\ClassNotFoundException;
  26. use think\exception\FuncNotFoundException;
  27. use think\helper\Str;
  28. /**
  29. * 容器管理类 支持PSR-11
  30. */
  31. class Container implements ContainerInterface, ArrayAccess, IteratorAggregate, Countable
  32. {
  33. /**
  34. * 容器对象实例
  35. * @var Container|Closure
  36. */
  37. protected static $instance;
  38. /**
  39. * 容器中的对象实例
  40. * @var array
  41. */
  42. protected $instances = [];
  43. /**
  44. * 容器绑定标识
  45. * @var array
  46. */
  47. protected $bind = [];
  48. /**
  49. * 容器回调
  50. * @var array
  51. */
  52. protected $invokeCallback = [];
  53. /**
  54. * 获取当前容器的实例(单例)
  55. * @access public
  56. * @return static
  57. */
  58. public static function getInstance()
  59. {
  60. if (is_null(static::$instance)) {
  61. static::$instance = new static;
  62. }
  63. if (static::$instance instanceof Closure) {
  64. return (static::$instance)();
  65. }
  66. return static::$instance;
  67. }
  68. /**
  69. * 设置当前容器的实例
  70. * @access public
  71. * @param object|Closure $instance
  72. * @return void
  73. */
  74. public static function setInstance($instance): void
  75. {
  76. static::$instance = $instance;
  77. }
  78. /**
  79. * 注册一个容器对象回调
  80. *
  81. * @param string|Closure $abstract
  82. * @param Closure|null $callback
  83. * @return void
  84. */
  85. public function resolving($abstract, Closure $callback = null): void
  86. {
  87. if ($abstract instanceof Closure) {
  88. $this->invokeCallback['*'][] = $abstract;
  89. return;
  90. }
  91. $abstract = $this->getAlias($abstract);
  92. $this->invokeCallback[$abstract][] = $callback;
  93. }
  94. /**
  95. * 获取容器中的对象实例 不存在则创建
  96. * @access public
  97. * @param string $abstract 类名或者标识
  98. * @param array|true $vars 变量
  99. * @param bool $newInstance 是否每次创建新的实例
  100. * @return object
  101. */
  102. public static function pull(string $abstract, array $vars = [], bool $newInstance = false)
  103. {
  104. return static::getInstance()->make($abstract, $vars, $newInstance);
  105. }
  106. /**
  107. * 获取容器中的对象实例
  108. * @access public
  109. * @param string $abstract 类名或者标识
  110. * @return object
  111. */
  112. public function get($abstract)
  113. {
  114. if ($this->has($abstract)) {
  115. return $this->make($abstract);
  116. }
  117. throw new ClassNotFoundException('class not exists: ' . $abstract, $abstract);
  118. }
  119. /**
  120. * 绑定一个类、闭包、实例、接口实现到容器
  121. * @access public
  122. * @param string|array $abstract 类标识、接口
  123. * @param mixed $concrete 要绑定的类、闭包或者实例
  124. * @return $this
  125. */
  126. public function bind($abstract, $concrete = null)
  127. {
  128. if (is_array($abstract)) {
  129. foreach ($abstract as $key => $val) {
  130. $this->bind($key, $val);
  131. }
  132. } elseif ($concrete instanceof Closure) {
  133. $this->bind[$abstract] = $concrete;
  134. } elseif (is_object($concrete)) {
  135. $this->instance($abstract, $concrete);
  136. } else {
  137. $abstract = $this->getAlias($abstract);
  138. if ($abstract != $concrete) {
  139. $this->bind[$abstract] = $concrete;
  140. }
  141. }
  142. return $this;
  143. }
  144. /**
  145. * 根据别名获取真实类名
  146. * @param string $abstract
  147. * @return string
  148. */
  149. public function getAlias(string $abstract): string
  150. {
  151. if (isset($this->bind[$abstract])) {
  152. $bind = $this->bind[$abstract];
  153. if (is_string($bind)) {
  154. return $this->getAlias($bind);
  155. }
  156. }
  157. return $abstract;
  158. }
  159. /**
  160. * 绑定一个类实例到容器
  161. * @access public
  162. * @param string $abstract 类名或者标识
  163. * @param object $instance 类的实例
  164. * @return $this
  165. */
  166. public function instance(string $abstract, $instance)
  167. {
  168. $abstract = $this->getAlias($abstract);
  169. $this->instances[$abstract] = $instance;
  170. return $this;
  171. }
  172. /**
  173. * 判断容器中是否存在类及标识
  174. * @access public
  175. * @param string $abstract 类名或者标识
  176. * @return bool
  177. */
  178. public function bound(string $abstract): bool
  179. {
  180. return isset($this->bind[$abstract]) || isset($this->instances[$abstract]);
  181. }
  182. /**
  183. * 判断容器中是否存在类及标识
  184. * @access public
  185. * @param string $name 类名或者标识
  186. * @return bool
  187. */
  188. public function has($name): bool
  189. {
  190. return $this->bound($name);
  191. }
  192. /**
  193. * 判断容器中是否存在对象实例
  194. * @access public
  195. * @param string $abstract 类名或者标识
  196. * @return bool
  197. */
  198. public function exists(string $abstract): bool
  199. {
  200. $abstract = $this->getAlias($abstract);
  201. return isset($this->instances[$abstract]);
  202. }
  203. /**
  204. * 创建类的实例 已经存在则直接获取
  205. * @access public
  206. * @param string $abstract 类名或者标识
  207. * @param array $vars 变量
  208. * @param bool $newInstance 是否每次创建新的实例
  209. * @return mixed
  210. */
  211. public function make(string $abstract, array $vars = [], bool $newInstance = false)
  212. {
  213. $abstract = $this->getAlias($abstract);
  214. if (isset($this->instances[$abstract]) && !$newInstance) {
  215. return $this->instances[$abstract];
  216. }
  217. if (isset($this->bind[$abstract]) && $this->bind[$abstract] instanceof Closure) {
  218. $object = $this->invokeFunction($this->bind[$abstract], $vars);
  219. } else {
  220. $object = $this->invokeClass($abstract, $vars);
  221. }
  222. if (!$newInstance) {
  223. $this->instances[$abstract] = $object;
  224. }
  225. return $object;
  226. }
  227. /**
  228. * 删除容器中的对象实例
  229. * @access public
  230. * @param string $name 类名或者标识
  231. * @return void
  232. */
  233. public function delete($name)
  234. {
  235. $name = $this->getAlias($name);
  236. if (isset($this->instances[$name])) {
  237. unset($this->instances[$name]);
  238. }
  239. }
  240. /**
  241. * 执行函数或者闭包方法 支持参数调用
  242. * @access public
  243. * @param string|Closure $function 函数或者闭包
  244. * @param array $vars 参数
  245. * @return mixed
  246. */
  247. public function invokeFunction($function, array $vars = [])
  248. {
  249. try {
  250. $reflect = new ReflectionFunction($function);
  251. } catch (ReflectionException $e) {
  252. throw new FuncNotFoundException("function not exists: {$function}()", $function, $e);
  253. }
  254. $args = $this->bindParams($reflect, $vars);
  255. return $function(...$args);
  256. }
  257. /**
  258. * 调用反射执行类的方法 支持参数绑定
  259. * @access public
  260. * @param mixed $method 方法
  261. * @param array $vars 参数
  262. * @param bool $accessible 设置是否可访问
  263. * @return mixed
  264. */
  265. public function invokeMethod($method, array $vars = [], bool $accessible = false)
  266. {
  267. if (is_array($method)) {
  268. [$class, $method] = $method;
  269. $class = is_object($class) ? $class : $this->invokeClass($class);
  270. } else {
  271. // 静态方法
  272. [$class, $method] = explode('::', $method);
  273. }
  274. try {
  275. $reflect = new ReflectionMethod($class, $method);
  276. } catch (ReflectionException $e) {
  277. $class = is_object($class) ? get_class($class) : $class;
  278. throw new FuncNotFoundException('method not exists: ' . $class . '::' . $method . '()', "{$class}::{$method}", $e);
  279. }
  280. $args = $this->bindParams($reflect, $vars);
  281. if ($accessible) {
  282. $reflect->setAccessible($accessible);
  283. }
  284. return $reflect->invokeArgs(is_object($class) ? $class : null, $args);
  285. }
  286. /**
  287. * 调用反射执行类的方法 支持参数绑定
  288. * @access public
  289. * @param object $instance 对象实例
  290. * @param mixed $reflect 反射类
  291. * @param array $vars 参数
  292. * @return mixed
  293. */
  294. public function invokeReflectMethod($instance, $reflect, array $vars = [])
  295. {
  296. $args = $this->bindParams($reflect, $vars);
  297. return $reflect->invokeArgs($instance, $args);
  298. }
  299. /**
  300. * 调用反射执行callable 支持参数绑定
  301. * @access public
  302. * @param mixed $callable
  303. * @param array $vars 参数
  304. * @param bool $accessible 设置是否可访问
  305. * @return mixed
  306. */
  307. public function invoke($callable, array $vars = [], bool $accessible = false)
  308. {
  309. if ($callable instanceof Closure) {
  310. return $this->invokeFunction($callable, $vars);
  311. } elseif (is_string($callable) && false === strpos($callable, '::')) {
  312. return $this->invokeFunction($callable, $vars);
  313. } else {
  314. return $this->invokeMethod($callable, $vars, $accessible);
  315. }
  316. }
  317. /**
  318. * 调用反射执行类的实例化 支持依赖注入
  319. * @access public
  320. * @param string $class 类名
  321. * @param array $vars 参数
  322. * @return mixed
  323. */
  324. public function invokeClass(string $class, array $vars = [])
  325. {
  326. try {
  327. $reflect = new ReflectionClass($class);
  328. } catch (ReflectionException $e) {
  329. throw new ClassNotFoundException('class not exists: ' . $class, $class, $e);
  330. }
  331. if ($reflect->hasMethod('__make')) {
  332. $method = $reflect->getMethod('__make');
  333. if ($method->isPublic() && $method->isStatic()) {
  334. $args = $this->bindParams($method, $vars);
  335. $object = $method->invokeArgs(null, $args);
  336. $this->invokeAfter($class, $object);
  337. return $object;
  338. }
  339. }
  340. $constructor = $reflect->getConstructor();
  341. $args = $constructor ? $this->bindParams($constructor, $vars) : [];
  342. $object = $reflect->newInstanceArgs($args);
  343. $this->invokeAfter($class, $object);
  344. return $object;
  345. }
  346. /**
  347. * 执行invokeClass回调
  348. * @access protected
  349. * @param string $class 对象类名
  350. * @param object $object 容器对象实例
  351. * @return void
  352. */
  353. protected function invokeAfter(string $class, $object): void
  354. {
  355. if (isset($this->invokeCallback['*'])) {
  356. foreach ($this->invokeCallback['*'] as $callback) {
  357. $callback($object, $this);
  358. }
  359. }
  360. if (isset($this->invokeCallback[$class])) {
  361. foreach ($this->invokeCallback[$class] as $callback) {
  362. $callback($object, $this);
  363. }
  364. }
  365. }
  366. /**
  367. * 绑定参数
  368. * @access protected
  369. * @param ReflectionFunctionAbstract $reflect 反射类
  370. * @param array $vars 参数
  371. * @return array
  372. */
  373. protected function bindParams(ReflectionFunctionAbstract $reflect, array $vars = []): array
  374. {
  375. if ($reflect->getNumberOfParameters() == 0) {
  376. return [];
  377. }
  378. // 判断数组类型 数字数组时按顺序绑定参数
  379. reset($vars);
  380. $type = key($vars) === 0 ? 1 : 0;
  381. $params = $reflect->getParameters();
  382. $args = [];
  383. foreach ($params as $param) {
  384. $name = $param->getName();
  385. $lowerName = Str::snake($name);
  386. $reflectionType = $param->getType();
  387. if ($reflectionType && $reflectionType->isBuiltin() === false) {
  388. $args[] = $this->getObjectParam($reflectionType->getName(), $vars);
  389. } elseif (1 == $type && !empty($vars)) {
  390. $args[] = array_shift($vars);
  391. } elseif (0 == $type && array_key_exists($name, $vars)) {
  392. $args[] = $vars[$name];
  393. } elseif (0 == $type && array_key_exists($lowerName, $vars)) {
  394. $args[] = $vars[$lowerName];
  395. } elseif ($param->isDefaultValueAvailable()) {
  396. $args[] = $param->getDefaultValue();
  397. } else {
  398. throw new InvalidArgumentException('method param miss:' . $name);
  399. }
  400. }
  401. return $args;
  402. }
  403. /**
  404. * 创建工厂对象实例
  405. * @param string $name 工厂类名
  406. * @param string $namespace 默认命名空间
  407. * @param array $args
  408. * @return mixed
  409. * @deprecated
  410. * @access public
  411. */
  412. public static function factory(string $name, string $namespace = '', ...$args)
  413. {
  414. $class = false !== strpos($name, '\\') ? $name : $namespace . ucwords($name);
  415. return Container::getInstance()->invokeClass($class, $args);
  416. }
  417. /**
  418. * 获取对象类型的参数值
  419. * @access protected
  420. * @param string $className 类名
  421. * @param array $vars 参数
  422. * @return mixed
  423. */
  424. protected function getObjectParam(string $className, array &$vars)
  425. {
  426. $array = $vars;
  427. $value = array_shift($array);
  428. if ($value instanceof $className) {
  429. $result = $value;
  430. array_shift($vars);
  431. } else {
  432. $result = $this->make($className);
  433. }
  434. return $result;
  435. }
  436. public function __set($name, $value)
  437. {
  438. $this->bind($name, $value);
  439. }
  440. public function __get($name)
  441. {
  442. return $this->get($name);
  443. }
  444. public function __isset($name): bool
  445. {
  446. return $this->exists($name);
  447. }
  448. public function __unset($name)
  449. {
  450. $this->delete($name);
  451. }
  452. public function offsetExists($key)
  453. {
  454. return $this->exists($key);
  455. }
  456. public function offsetGet($key)
  457. {
  458. return $this->make($key);
  459. }
  460. public function offsetSet($key, $value)
  461. {
  462. $this->bind($key, $value);
  463. }
  464. public function offsetUnset($key)
  465. {
  466. $this->delete($key);
  467. }
  468. //Countable
  469. public function count()
  470. {
  471. return count($this->instances);
  472. }
  473. //IteratorAggregate
  474. public function getIterator()
  475. {
  476. return new ArrayIterator($this->instances);
  477. }
  478. }