설명 없음
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Container.php 17KB

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