Container.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2019 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. $this->bind[$abstract] = $concrete;
  139. }
  140. return $this;
  141. }
  142. /**
  143. * 根据别名获取真实类名
  144. * @param string $abstract
  145. * @return string
  146. */
  147. public function getAlias(string $abstract): string
  148. {
  149. if (isset($this->bind[$abstract])) {
  150. $bind = $this->bind[$abstract];
  151. if (is_string($bind)) {
  152. return $this->getAlias($bind);
  153. }
  154. }
  155. return $abstract;
  156. }
  157. /**
  158. * 绑定一个类实例到容器
  159. * @access public
  160. * @param string $abstract 类名或者标识
  161. * @param object $instance 类的实例
  162. * @return $this
  163. */
  164. public function instance(string $abstract, $instance)
  165. {
  166. $abstract = $this->getAlias($abstract);
  167. $this->instances[$abstract] = $instance;
  168. return $this;
  169. }
  170. /**
  171. * 判断容器中是否存在类及标识
  172. * @access public
  173. * @param string $abstract 类名或者标识
  174. * @return bool
  175. */
  176. public function bound(string $abstract): bool
  177. {
  178. return isset($this->bind[$abstract]) || isset($this->instances[$abstract]);
  179. }
  180. /**
  181. * 判断容器中是否存在类及标识
  182. * @access public
  183. * @param string $name 类名或者标识
  184. * @return bool
  185. */
  186. public function has($name): bool
  187. {
  188. return $this->bound($name);
  189. }
  190. /**
  191. * 判断容器中是否存在对象实例
  192. * @access public
  193. * @param string $abstract 类名或者标识
  194. * @return bool
  195. */
  196. public function exists(string $abstract): bool
  197. {
  198. $abstract = $this->getAlias($abstract);
  199. return isset($this->instances[$abstract]);
  200. }
  201. /**
  202. * 创建类的实例 已经存在则直接获取
  203. * @access public
  204. * @param string $abstract 类名或者标识
  205. * @param array $vars 变量
  206. * @param bool $newInstance 是否每次创建新的实例
  207. * @return mixed
  208. */
  209. public function make(string $abstract, array $vars = [], bool $newInstance = false)
  210. {
  211. $abstract = $this->getAlias($abstract);
  212. if (isset($this->instances[$abstract]) && !$newInstance) {
  213. return $this->instances[$abstract];
  214. }
  215. if (isset($this->bind[$abstract]) && $this->bind[$abstract] instanceof Closure) {
  216. $object = $this->invokeFunction($this->bind[$abstract], $vars);
  217. } else {
  218. $object = $this->invokeClass($abstract, $vars);
  219. }
  220. if (!$newInstance) {
  221. $this->instances[$abstract] = $object;
  222. }
  223. return $object;
  224. }
  225. /**
  226. * 删除容器中的对象实例
  227. * @access public
  228. * @param string $name 类名或者标识
  229. * @return void
  230. */
  231. public function delete($name)
  232. {
  233. $name = $this->getAlias($name);
  234. if (isset($this->instances[$name])) {
  235. unset($this->instances[$name]);
  236. }
  237. }
  238. /**
  239. * 执行函数或者闭包方法 支持参数调用
  240. * @access public
  241. * @param string|Closure $function 函数或者闭包
  242. * @param array $vars 参数
  243. * @return mixed
  244. */
  245. public function invokeFunction($function, array $vars = [])
  246. {
  247. try {
  248. $reflect = new ReflectionFunction($function);
  249. } catch (ReflectionException $e) {
  250. throw new FuncNotFoundException("function not exists: {$function}()", $function, $e);
  251. }
  252. $args = $this->bindParams($reflect, $vars);
  253. return $function(...$args);
  254. }
  255. /**
  256. * 调用反射执行类的方法 支持参数绑定
  257. * @access public
  258. * @param mixed $method 方法
  259. * @param array $vars 参数
  260. * @param bool $accessible 设置是否可访问
  261. * @return mixed
  262. */
  263. public function invokeMethod($method, array $vars = [], bool $accessible = false)
  264. {
  265. if (is_array($method)) {
  266. [$class, $method] = $method;
  267. $class = is_object($class) ? $class : $this->invokeClass($class);
  268. } else {
  269. // 静态方法
  270. [$class, $method] = explode('::', $method);
  271. }
  272. try {
  273. $reflect = new ReflectionMethod($class, $method);
  274. } catch (ReflectionException $e) {
  275. $class = is_object($class) ? get_class($class) : $class;
  276. $message = sprintf('method not exists: %d::%d()', $class, $method);
  277. throw new FuncNotFoundException($message, "{$class}::{$method}", $e);
  278. }
  279. $args = $this->bindParams($reflect, $vars);
  280. if ($accessible) {
  281. $reflect->setAccessible($accessible);
  282. }
  283. return $reflect->invokeArgs(is_object($class) ? $class : null, $args);
  284. }
  285. /**
  286. * 调用反射执行类的方法 支持参数绑定
  287. * @access public
  288. * @param object $instance 对象实例
  289. * @param mixed $reflect 反射类
  290. * @param array $vars 参数
  291. * @return mixed
  292. */
  293. public function invokeReflectMethod($instance, $reflect, array $vars = [])
  294. {
  295. $args = $this->bindParams($reflect, $vars);
  296. return $reflect->invokeArgs($instance, $args);
  297. }
  298. /**
  299. * 调用反射执行callable 支持参数绑定
  300. * @access public
  301. * @param mixed $callable
  302. * @param array $vars 参数
  303. * @param bool $accessible 设置是否可访问
  304. * @return mixed
  305. */
  306. public function invoke($callable, array $vars = [], bool $accessible = false)
  307. {
  308. if ($callable instanceof Closure) {
  309. return $this->invokeFunction($callable, $vars);
  310. } elseif (is_string($callable) && false === strpos($callable, '::')) {
  311. return $this->invokeFunction($callable, $vars);
  312. } else {
  313. return $this->invokeMethod($callable, $vars, $accessible);
  314. }
  315. }
  316. /**
  317. * 调用反射执行类的实例化 支持依赖注入
  318. * @access public
  319. * @param string $class 类名
  320. * @param array $vars 参数
  321. * @return mixed
  322. */
  323. public function invokeClass(string $class, array $vars = [])
  324. {
  325. try {
  326. $reflect = new ReflectionClass($class);
  327. } catch (ReflectionException $e) {
  328. throw new ClassNotFoundException('class not exists: ' . $class, $class, $e);
  329. }
  330. if ($reflect->hasMethod('__make')) {
  331. $method = $reflect->getMethod('__make');
  332. if ($method->isPublic() && $method->isStatic()) {
  333. $args = $this->bindParams($method, $vars);
  334. return $method->invokeArgs(null, $args);
  335. }
  336. }
  337. $constructor = $reflect->getConstructor();
  338. $args = $constructor ? $this->bindParams($constructor, $vars) : [];
  339. $object = $reflect->newInstanceArgs($args);
  340. $this->invokeAfter($class, $object);
  341. return $object;
  342. }
  343. /**
  344. * 执行invokeClass回调
  345. * @access protected
  346. * @param string $class 对象类名
  347. * @param object $object 容器对象实例
  348. * @return void
  349. */
  350. protected function invokeAfter(string $class, $object): void
  351. {
  352. if (isset($this->invokeCallback['*'])) {
  353. foreach ($this->invokeCallback['*'] as $callback) {
  354. $callback($object, $this);
  355. }
  356. }
  357. if (isset($this->invokeCallback[$class])) {
  358. foreach ($this->invokeCallback[$class] as $callback) {
  359. $callback($object, $this);
  360. }
  361. }
  362. }
  363. /**
  364. * 绑定参数
  365. * @access protected
  366. * @param ReflectionFunctionAbstract $reflect 反射类
  367. * @param array $vars 参数
  368. * @return array
  369. */
  370. protected function bindParams(ReflectionFunctionAbstract $reflect, array $vars = []): array
  371. {
  372. if ($reflect->getNumberOfParameters() == 0) {
  373. return [];
  374. }
  375. // 判断数组类型 数字数组时按顺序绑定参数
  376. reset($vars);
  377. $type = key($vars) === 0 ? 1 : 0;
  378. $params = $reflect->getParameters();
  379. $args = [];
  380. foreach ($params as $param) {
  381. $name = $param->getName();
  382. $lowerName = Str::snake($name);
  383. $class = $param->getClass();
  384. if ($class) {
  385. $args[] = $this->getObjectParam($class->getName(), $vars);
  386. } elseif (1 == $type && !empty($vars)) {
  387. $args[] = array_shift($vars);
  388. } elseif (0 == $type && isset($vars[$name])) {
  389. $args[] = $vars[$name];
  390. } elseif (0 == $type && isset($vars[$lowerName])) {
  391. $args[] = $vars[$lowerName];
  392. } elseif ($param->isDefaultValueAvailable()) {
  393. $args[] = $param->getDefaultValue();
  394. } else {
  395. throw new InvalidArgumentException('method param miss:' . $name);
  396. }
  397. }
  398. return $args;
  399. }
  400. /**
  401. * 创建工厂对象实例
  402. * @param string $name 工厂类名
  403. * @param string $namespace 默认命名空间
  404. * @param array $args
  405. * @return mixed
  406. * @deprecated
  407. * @access public
  408. */
  409. public static function factory(string $name, string $namespace = '', ...$args)
  410. {
  411. $class = false !== strpos($name, '\\') ? $name : $namespace . ucwords($name);
  412. return Container::getInstance()->invokeClass($class, $args);
  413. }
  414. /**
  415. * 获取对象类型的参数值
  416. * @access protected
  417. * @param string $className 类名
  418. * @param array $vars 参数
  419. * @return mixed
  420. */
  421. protected function getObjectParam(string $className, array &$vars)
  422. {
  423. $array = $vars;
  424. $value = array_shift($array);
  425. if ($value instanceof $className) {
  426. $result = $value;
  427. array_shift($vars);
  428. } else {
  429. $result = $this->make($className);
  430. }
  431. return $result;
  432. }
  433. public function __set($name, $value)
  434. {
  435. $this->bind($name, $value);
  436. }
  437. public function __get($name)
  438. {
  439. return $this->get($name);
  440. }
  441. public function __isset($name): bool
  442. {
  443. return $this->exists($name);
  444. }
  445. public function __unset($name)
  446. {
  447. $this->delete($name);
  448. }
  449. public function offsetExists($key)
  450. {
  451. return $this->exists($key);
  452. }
  453. public function offsetGet($key)
  454. {
  455. return $this->make($key);
  456. }
  457. public function offsetSet($key, $value)
  458. {
  459. $this->bind($key, $value);
  460. }
  461. public function offsetUnset($key)
  462. {
  463. $this->delete($key);
  464. }
  465. //Countable
  466. public function count()
  467. {
  468. return count($this->instances);
  469. }
  470. //IteratorAggregate
  471. public function getIterator()
  472. {
  473. return new ArrayIterator($this->instances);
  474. }
  475. }