Container.php 15 KB

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