├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src
├── Container.php
├── Facade.php
└── exception
│ ├── ClassNotFoundException.php
│ └── FuncNotFoundException.php
└── tests
├── ContainerTest.php
└── bootstrap.php
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | vendor
3 | composer.lock
4 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | dist: xenial
2 | language: php
3 |
4 | matrix:
5 | fast_finish: true
6 | include:
7 | - php: 8.0
8 | - php: 8.1
9 | - php: 8.2
10 | - php: 8.3
11 | - php: 8.4
12 |
13 | cache:
14 | directories:
15 | - $HOME/.composer/cache
16 |
17 |
18 | install:
19 | - travis_retry composer update --prefer-dist --no-interaction --prefer-stable --no-suggest
20 |
21 | script:
22 | - vendor/bin/phpunit --coverage-clover build/logs/coverage.xml
23 |
24 | after_script:
25 | - travis_retry wget https://scrutinizer-ci.com/ocular.phar
26 | - php ocular.phar code-coverage:upload --format=php-clover build/logs/coverage.xml
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | PHP Container & Facade Manager( Support PSR-11)
2 | ===============
3 |
4 |
5 | ## 安装
6 | ~~~
7 | composer require topthink/think-container
8 | ~~~
9 |
10 | ## 特性
11 |
12 | * 支持PSR-11规范
13 | * 支持依赖注入
14 | * 支持Facade门面
15 | * 支持容器对象绑定
16 | * 支持闭包绑定
17 | * 支持接口绑定
18 |
19 | ## Container
20 | ~~~
21 | // 获取容器实例
22 | $container = \think\Container::getInstance();
23 | // 绑定一个类、闭包、实例、接口实现到容器
24 | $container->bind('cache', '\app\common\Cache');
25 | // 判断是否存在对象实例
26 | $container->has('cache');
27 | // 从容器中获取对象的唯一实例
28 | $container->get('cache');
29 | // 从容器中获取对象,没有则自动实例化
30 | $container->make('cache');
31 | // 删除容器中的对象实例
32 | $container->delete('cache');
33 | // 执行某个方法或者闭包 支持依赖注入
34 | $container->invoke($callable, $vars);
35 | // 执行某个类的实例化 支持依赖注入
36 | $container->invokeClass($class, $vars);
37 | // 静态方法获取容器对象实例 不存在则自动实例化
38 | \think\Container::pull('cache');
39 | ~~~
40 |
41 | 对象化操作
42 | ~~~
43 | // 获取容器实例
44 | $container = \think\Container::getInstance();
45 | // 绑定一个类、闭包、实例、接口实现到容器
46 | $container->cache = '\app\common\Cache';
47 | // 判断是否存在对象实例
48 | isset($container->cache);
49 | // 从容器中获取对象的唯一实例
50 | $container->cache;
51 | // 删除容器中的对象实例
52 | unset($container->cache);
53 | ~~~
54 |
55 | ## Facade
56 |
57 |
58 | 定义一个`app\facade\App`类之后,即可以静态方式调用`\think\App`类的动态方法
59 | ~~~
60 | =8.0",
13 | "psr/container": "^2.0",
14 | "topthink/think-helper":"^3.1"
15 | },
16 | "require-dev": {
17 | "phpunit/phpunit": "^9.5"
18 | },
19 | "autoload": {
20 | "psr-4": {
21 | "think\\": "src"
22 | },
23 | "files": [
24 | ]
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/phpunit.xml.dist:
--------------------------------------------------------------------------------
1 |
2 |
15 |
16 |
17 | ./tests
18 |
19 |
20 |
21 |
22 | ./src
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/src/Container.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 | declare (strict_types = 1);
12 |
13 | namespace think;
14 |
15 | use ArrayAccess;
16 | use ArrayIterator;
17 | use Closure;
18 | use Countable;
19 | use InvalidArgumentException;
20 | use IteratorAggregate;
21 | use Psr\Container\ContainerInterface;
22 | use ReflectionClass;
23 | use ReflectionException;
24 | use ReflectionFunction;
25 | use ReflectionFunctionAbstract;
26 | use ReflectionMethod;
27 | use ReflectionNamedType;
28 | use ReflectionParameter;
29 | use think\exception\ClassNotFoundException;
30 | use think\exception\FuncNotFoundException;
31 | use think\helper\Str;
32 | use Throwable;
33 | use Traversable;
34 |
35 | /**
36 | * 容器管理类 支持PSR-11
37 | */
38 | class Container implements ContainerInterface, ArrayAccess, IteratorAggregate, Countable
39 | {
40 | /**
41 | * 容器对象实例
42 | * @var Container|Closure
43 | */
44 | protected static $instance;
45 |
46 | /**
47 | * 容器中的对象实例
48 | * @var array
49 | */
50 | protected $instances = [];
51 |
52 | /**
53 | * 容器绑定标识
54 | * @var array
55 | */
56 | protected $bind = [];
57 |
58 | /**
59 | * 容器回调
60 | * @var array
61 | */
62 | protected $invokeCallback = [];
63 |
64 | /**
65 | * 获取当前容器的实例(单例)
66 | * @access public
67 | * @return static
68 | */
69 | public static function getInstance()
70 | {
71 | if (is_null(static::$instance)) {
72 | static::$instance = new static;
73 | }
74 |
75 | if (static::$instance instanceof Closure) {
76 | return (static::$instance)();
77 | }
78 |
79 | return static::$instance;
80 | }
81 |
82 | /**
83 | * 设置当前容器的实例
84 | * @access public
85 | * @param object|Closure $instance
86 | * @return void
87 | */
88 | public static function setInstance($instance): void
89 | {
90 | static::$instance = $instance;
91 | }
92 |
93 | /**
94 | * 注册一个容器对象回调
95 | *
96 | * @param string|Closure $abstract
97 | * @param Closure|null $callback
98 | * @return void
99 | */
100 | public function resolving(string|Closure $abstract, ?Closure $callback = null): void
101 | {
102 | if ($abstract instanceof Closure) {
103 | $this->invokeCallback['*'][] = $abstract;
104 | return;
105 | }
106 |
107 | $abstract = $this->getAlias($abstract);
108 |
109 | $this->invokeCallback[$abstract][] = $callback;
110 | }
111 |
112 | /**
113 | * 获取容器中的对象实例 不存在则创建
114 | * @template T
115 | * @param string|class-string $abstract 类名或者标识
116 | * @param array $vars 变量
117 | * @param bool $newInstance 是否每次创建新的实例
118 | * @return T|object
119 | */
120 | public static function pull(string $abstract, array $vars = [], bool $newInstance = false)
121 | {
122 | return static::getInstance()->make($abstract, $vars, $newInstance);
123 | }
124 |
125 | /**
126 | * 获取容器中的对象实例
127 | * @template T
128 | * @param string|class-string $abstract 类名或者标识
129 | * @return T|object
130 | */
131 | public function get(string $abstract)
132 | {
133 | if ($this->has($abstract)) {
134 | return $this->make($abstract);
135 | }
136 |
137 | throw new ClassNotFoundException('class not exists: ' . $abstract, $abstract);
138 | }
139 |
140 | /**
141 | * 绑定一个类、闭包、实例、接口实现到容器
142 | * @access public
143 | * @param string|array $abstract 类标识、接口
144 | * @param mixed $concrete 要绑定的类、闭包或者实例
145 | * @return $this
146 | */
147 | public function bind(string|array $abstract, $concrete = null)
148 | {
149 | if (is_array($abstract)) {
150 | foreach ($abstract as $key => $val) {
151 | $this->bind($key, $val);
152 | }
153 | } elseif ($concrete instanceof Closure) {
154 | $this->bind[$abstract] = $concrete;
155 | } elseif (is_object($concrete)) {
156 | $this->instance($abstract, $concrete);
157 | } else {
158 | $abstract = $this->getAlias($abstract);
159 | if ($abstract != $concrete) {
160 | $this->bind[$abstract] = $concrete;
161 | }
162 | }
163 |
164 | return $this;
165 | }
166 |
167 | /**
168 | * 根据别名获取真实类名
169 | * @param string $abstract
170 | * @return string
171 | */
172 | public function getAlias(string $abstract): string
173 | {
174 | if (isset($this->bind[$abstract])) {
175 | $bind = $this->bind[$abstract];
176 |
177 | if (is_string($bind)) {
178 | return $this->getAlias($bind);
179 | }
180 | }
181 |
182 | return $abstract;
183 | }
184 |
185 | /**
186 | * 绑定一个类实例到容器
187 | * @access public
188 | * @param string $abstract 类名或者标识
189 | * @param object $instance 类的实例
190 | * @return $this
191 | */
192 | public function instance(string $abstract, $instance)
193 | {
194 | $abstract = $this->getAlias($abstract);
195 |
196 | $this->instances[$abstract] = $instance;
197 |
198 | return $this;
199 | }
200 |
201 | /**
202 | * 判断容器中是否存在类及标识
203 | * @access public
204 | * @param string $abstract 类名或者标识
205 | * @return bool
206 | */
207 | public function bound(string $abstract): bool
208 | {
209 | return isset($this->bind[$abstract]) || isset($this->instances[$abstract]);
210 | }
211 |
212 | /**
213 | * 判断容器中是否存在类及标识
214 | * @access public
215 | * @param string $name 类名或者标识
216 | * @return bool
217 | */
218 | public function has(string $name): bool
219 | {
220 | return $this->bound($name);
221 | }
222 |
223 | /**
224 | * 判断容器中是否存在对象实例
225 | * @access public
226 | * @param string $abstract 类名或者标识
227 | * @return bool
228 | */
229 | public function exists(string $abstract): bool
230 | {
231 | $abstract = $this->getAlias($abstract);
232 |
233 | return isset($this->instances[$abstract]);
234 | }
235 |
236 | /**
237 | * 创建类的实例 已经存在则直接获取
238 | * @template T
239 | * @param string|class-string $abstract 类名或者标识
240 | * @param array $vars 变量
241 | * @param bool $newInstance 是否每次创建新的实例
242 | * @return T|object
243 | */
244 | public function make(string $abstract, array $vars = [], bool $newInstance = false)
245 | {
246 | $abstract = $this->getAlias($abstract);
247 |
248 | if (isset($this->instances[$abstract]) && !$newInstance) {
249 | return $this->instances[$abstract];
250 | }
251 |
252 | if (isset($this->bind[$abstract]) && $this->bind[$abstract] instanceof Closure) {
253 | $object = $this->invokeFunction($this->bind[$abstract], $vars);
254 | } else {
255 | $object = $this->invokeClass($abstract, $vars);
256 | }
257 |
258 | $this->invokeAfter($abstract, $object);
259 |
260 | if (!$newInstance) {
261 | $this->instances[$abstract] = $object;
262 | }
263 |
264 | return $object;
265 | }
266 |
267 | /**
268 | * 删除容器中的对象实例
269 | * @access public
270 | * @param string $name 类名或者标识
271 | * @return void
272 | */
273 | public function delete(string $name)
274 | {
275 | $name = $this->getAlias($name);
276 |
277 | if (isset($this->instances[$name])) {
278 | unset($this->instances[$name]);
279 | }
280 | }
281 |
282 | /**
283 | * 执行函数或者闭包方法 支持参数调用
284 | * @access public
285 | * @param string|Closure $function 函数或者闭包
286 | * @param array $vars 参数
287 | * @return mixed
288 | */
289 | public function invokeFunction(string|Closure $function, array $vars = [])
290 | {
291 | try {
292 | $reflect = new ReflectionFunction($function);
293 | } catch (ReflectionException $e) {
294 | throw new FuncNotFoundException("function not exists: {$function}()", $function, $e);
295 | }
296 |
297 | $args = $this->bindParams($reflect, $vars);
298 |
299 | return $function(...$args);
300 | }
301 |
302 | /**
303 | * 调用反射执行类的方法 支持参数绑定
304 | * @access public
305 | * @param mixed $method 方法
306 | * @param array $vars 参数
307 | * @param bool $accessible 设置是否可访问
308 | * @return mixed
309 | */
310 | public function invokeMethod($method, array $vars = [], bool $accessible = false)
311 | {
312 | if (is_array($method)) {
313 | [$class, $method] = $method;
314 |
315 | $class = is_object($class) ? $class : $this->invokeClass($class);
316 | } else {
317 | // 静态方法
318 | [$class, $method] = explode('::', $method);
319 | }
320 |
321 | try {
322 | $reflect = new ReflectionMethod($class, $method);
323 | } catch (ReflectionException $e) {
324 | $class = is_object($class) ? $class::class : $class;
325 | throw new FuncNotFoundException('method not exists: ' . $class . '::' . $method . '()', "{$class}::{$method}", $e);
326 | }
327 |
328 | $args = $this->bindParams($reflect, $vars);
329 |
330 | if ($accessible) {
331 | $reflect->setAccessible($accessible);
332 | }
333 |
334 | return $reflect->invokeArgs(is_object($class) ? $class : null, $args);
335 | }
336 |
337 | /**
338 | * 调用反射执行类的方法 支持参数绑定
339 | * @access public
340 | * @param object $instance 对象实例
341 | * @param mixed $reflect 反射类
342 | * @param array $vars 参数
343 | * @return mixed
344 | */
345 | public function invokeReflectMethod($instance, $reflect, array $vars = [])
346 | {
347 | $args = $this->bindParams($reflect, $vars);
348 |
349 | return $reflect->invokeArgs($instance, $args);
350 | }
351 |
352 | /**
353 | * 调用反射执行callable 支持参数绑定
354 | * @access public
355 | * @param mixed $callable
356 | * @param array $vars 参数
357 | * @param bool $accessible 设置是否可访问
358 | * @return mixed
359 | */
360 | public function invoke($callable, array $vars = [], bool $accessible = false)
361 | {
362 | if ($callable instanceof Closure) {
363 | return $this->invokeFunction($callable, $vars);
364 | } elseif (is_string($callable) && !str_contains($callable, '::')) {
365 | return $this->invokeFunction($callable, $vars);
366 | } else {
367 | return $this->invokeMethod($callable, $vars, $accessible);
368 | }
369 | }
370 |
371 | /**
372 | * 调用反射执行类的实例化 支持依赖注入
373 | * @access public
374 | * @param string $class 类名
375 | * @param array $vars 参数
376 | * @return mixed
377 | */
378 | public function invokeClass(string $class, array $vars = [])
379 | {
380 | try {
381 | $reflect = new ReflectionClass($class);
382 | } catch (ReflectionException $e) {
383 | throw new ClassNotFoundException('class not exists: ' . $class, $class, $e);
384 | }
385 |
386 | if ($reflect->hasMethod('__make')) {
387 | $method = $reflect->getMethod('__make');
388 | if ($method->isPublic() && $method->isStatic()) {
389 | $args = $this->bindParams($method, $vars);
390 | return $method->invokeArgs(null, $args);
391 | }
392 | }
393 |
394 | $constructor = $reflect->getConstructor();
395 |
396 | $args = $constructor ? $this->bindParams($constructor, $vars) : [];
397 |
398 | return $reflect->newInstanceArgs($args);
399 | }
400 |
401 | /**
402 | * 执行invokeClass回调
403 | * @access protected
404 | * @param string $class 对象类名
405 | * @param object $object 容器对象实例
406 | * @return void
407 | */
408 | protected function invokeAfter(string $class, $object): void
409 | {
410 | if (isset($this->invokeCallback['*'])) {
411 | foreach ($this->invokeCallback['*'] as $callback) {
412 | $callback($object, $this);
413 | }
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 | * 绑定参数
425 | * @access protected
426 | * @param ReflectionFunctionAbstract $reflect 反射类
427 | * @param array $vars 参数
428 | * @return array
429 | */
430 | protected function bindParams(ReflectionFunctionAbstract $reflect, array $vars = []): array
431 | {
432 | if ($reflect->getNumberOfParameters() == 0) {
433 | return [];
434 | }
435 |
436 | // 判断数组类型 数字数组时按顺序绑定参数
437 | $type = array_is_list($vars) ? 1 : 0;
438 | $params = $reflect->getParameters();
439 | $args = [];
440 |
441 | foreach ($params as $param) {
442 | $name = $param->getName();
443 | $lowerName = Str::snake($name);
444 | $reflectionType = $param->getType();
445 |
446 | if ($param->isVariadic()) {
447 | return array_merge($args, array_values($vars));
448 | } elseif ($reflectionType && $reflectionType instanceof ReflectionNamedType && $reflectionType->isBuiltin() === false) {
449 | $className = $reflectionType->getName();
450 | if ($className == 'self') {
451 | $className = $param->getDeclaringClass()->getName();
452 | }
453 | $args[] = $this->getObjectParam($className, $vars, $param);
454 | } elseif (1 == $type && !empty($vars)) {
455 | $args[] = array_shift($vars);
456 | } elseif (0 == $type && array_key_exists($name, $vars)) {
457 | $args[] = $vars[$name];
458 | } elseif (0 == $type && array_key_exists($lowerName, $vars)) {
459 | $args[] = $vars[$lowerName];
460 | } elseif ($param->isDefaultValueAvailable()) {
461 | $args[] = $param->getDefaultValue();
462 | } else {
463 | throw new InvalidArgumentException('method param miss:' . $name);
464 | }
465 | }
466 |
467 | return $args;
468 | }
469 |
470 | /**
471 | * 创建工厂对象实例
472 | * @param string $name 工厂类名
473 | * @param string $namespace 默认命名空间
474 | * @param array $args
475 | * @return mixed
476 | * @deprecated
477 | * @access public
478 | */
479 | public static function factory(string $name, string $namespace = '', ...$args)
480 | {
481 | $class = str_contains($name, '\\') ? $name : $namespace . ucwords($name);
482 |
483 | return Container::getInstance()->invokeClass($class, $args);
484 | }
485 |
486 | /**
487 | * 获取对象类型的参数值
488 | * @access protected
489 | * @param string $className 类名
490 | * @param array $vars 参数
491 | * @param ReflectionParameter $param
492 | * @return mixed
493 | */
494 | protected function getObjectParam(string $className, array &$vars, ReflectionParameter $param)
495 | {
496 | $array = $vars;
497 | $value = array_shift($array);
498 |
499 | if ($value instanceof $className) {
500 | $result = $value;
501 | array_shift($vars);
502 | } else {
503 | if ($param->isDefaultValueAvailable()) {
504 | $result = $this->bound($className) ? $this->make($className) : $param->getDefaultValue();
505 | } else {
506 | $result = $this->make($className);
507 | }
508 | }
509 |
510 | return $result;
511 | }
512 |
513 | public function __set($name, $value)
514 | {
515 | $this->bind($name, $value);
516 | }
517 |
518 | public function __get($name)
519 | {
520 | return $this->get($name);
521 | }
522 |
523 | public function __isset($name): bool
524 | {
525 | return $this->exists($name);
526 | }
527 |
528 | public function __unset($name)
529 | {
530 | $this->delete($name);
531 | }
532 |
533 | public function offsetExists(mixed $key): bool
534 | {
535 | return $this->exists($key);
536 | }
537 |
538 | public function offsetGet(mixed $key): mixed
539 | {
540 | return $this->make($key);
541 | }
542 |
543 | public function offsetSet(mixed $key, mixed $value): void
544 | {
545 | $this->bind($key, $value);
546 | }
547 |
548 | public function offsetUnset(mixed $key): void
549 | {
550 | $this->delete($key);
551 | }
552 |
553 | //Countable
554 | public function count(): int
555 | {
556 | return count($this->instances);
557 | }
558 |
559 | //IteratorAggregate
560 | public function getIterator(): Traversable
561 | {
562 | return new ArrayIterator($this->instances);
563 | }
564 | }
565 |
--------------------------------------------------------------------------------
/src/Facade.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 | namespace think;
12 |
13 | /**
14 | * Facade管理类
15 | */
16 | class Facade
17 | {
18 | /**
19 | * 始终创建新的对象实例
20 | * @var bool
21 | */
22 | protected static $alwaysNewInstance;
23 |
24 | /**
25 | * 创建Facade实例
26 | * @static
27 | * @access protected
28 | * @param string $class 类名或标识
29 | * @param array $args 变量
30 | * @param bool $newInstance 是否每次创建新的实例
31 | * @return object
32 | */
33 | protected static function createFacade(string $class = '', array $args = [], bool $newInstance = false)
34 | {
35 | $class = $class ?: static::class;
36 |
37 | $facadeClass = static::getFacadeClass();
38 |
39 | if ($facadeClass) {
40 | $class = $facadeClass;
41 | }
42 |
43 | if (static::$alwaysNewInstance) {
44 | $newInstance = true;
45 | }
46 |
47 | return Container::getInstance()->make($class, $args, $newInstance);
48 | }
49 |
50 | /**
51 | * 获取当前Facade对应类名
52 | * @access protected
53 | * @return string
54 | */
55 | protected static function getFacadeClass()
56 | {
57 | }
58 |
59 | /**
60 | * 带参数实例化当前Facade类
61 | * @access public
62 | * @return object
63 | */
64 | public static function instance(...$args)
65 | {
66 | if (__CLASS__ != static::class) {
67 | return self::createFacade('', $args);
68 | }
69 | }
70 |
71 | /**
72 | * 调用类的实例
73 | * @access public
74 | * @param string $class 类名或者标识
75 | * @param array|true $args 变量
76 | * @param bool $newInstance 是否每次创建新的实例
77 | * @return object
78 | */
79 | public static function make(string $class, $args = [], $newInstance = false)
80 | {
81 | if (__CLASS__ != static::class) {
82 | return self::__callStatic('make', func_get_args());
83 | }
84 |
85 | if (true === $args) {
86 | // 总是创建新的实例化对象
87 | $newInstance = true;
88 | $args = [];
89 | }
90 |
91 | return self::createFacade($class, $args, $newInstance);
92 | }
93 |
94 | // 调用实际类的方法
95 | public static function __callStatic($method, $params)
96 | {
97 | return call_user_func_array([static::createFacade(), $method], $params);
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/src/exception/ClassNotFoundException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | use Psr\Container\NotFoundExceptionInterface;
15 | use RuntimeException;
16 | use Throwable;
17 |
18 | class ClassNotFoundException extends RuntimeException implements NotFoundExceptionInterface
19 | {
20 | public function __construct(string $message, protected string $class = '', ?Throwable $previous = null)
21 | {
22 | $this->message = $message;
23 |
24 | parent::__construct($message, 0, $previous);
25 | }
26 |
27 | /**
28 | * 获取类名
29 | * @access public
30 | * @return string
31 | */
32 | public function getClass()
33 | {
34 | return $this->class;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/exception/FuncNotFoundException.php:
--------------------------------------------------------------------------------
1 | message = $message;
14 |
15 | parent::__construct($message, 0, $previous);
16 | }
17 |
18 | /**
19 | * 获取方法名
20 | * @access public
21 | * @return string
22 | */
23 | public function getFunc()
24 | {
25 | return $this->func;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/tests/ContainerTest.php:
--------------------------------------------------------------------------------
1 | name = $name;
22 | }
23 |
24 | public function some(Container $container)
25 | {
26 | }
27 |
28 | protected function protectionFun()
29 | {
30 | return true;
31 | }
32 |
33 | public static function test(Container $container)
34 | {
35 | return $container;
36 | }
37 |
38 | public static function make(self $taylor)
39 | {
40 | return $taylor;
41 | }
42 |
43 | public static function __make()
44 | {
45 | return new self('Taylor');
46 | }
47 | }
48 |
49 | class SomeClass
50 | {
51 | public $container;
52 |
53 | public $count = 0;
54 |
55 | public function __construct(Container $container)
56 | {
57 | $this->container = $container;
58 | }
59 | }
60 |
61 | class WithDefaultValues
62 | {
63 | public $container;
64 |
65 | public function __construct(?Container $container = null)
66 | {
67 | $this->container = $container;
68 | }
69 |
70 | /**
71 | * 有默认值且类存在,但无法注入
72 | */
73 | public static function classExistsButCannotBeInjected(?Closure $closure = null)
74 | {
75 | return $closure;
76 | }
77 | }
78 |
79 | class ContainerTest extends TestCase
80 | {
81 | protected function tearDown(): void
82 | {
83 | Container::setInstance(null);
84 | }
85 |
86 | public function testClosureResolution()
87 | {
88 | $container = new Container;
89 |
90 | Container::setInstance($container);
91 |
92 | $container->bind('name', function () {
93 | return 'Taylor';
94 | });
95 |
96 | $this->assertEquals('Taylor', $container->make('name'));
97 |
98 | $this->assertEquals('Taylor', Container::pull('name'));
99 | }
100 |
101 | public function testGet()
102 | {
103 | $container = new Container;
104 |
105 | $this->expectException(ClassNotFoundException::class);
106 | $this->expectExceptionMessage('class not exists: name');
107 | $container->get('name');
108 |
109 | $container->bind('name', function () {
110 | return 'Taylor';
111 | });
112 |
113 | $this->assertSame('Taylor', $container->get('name'));
114 | }
115 |
116 | public function testExist()
117 | {
118 | $container = new Container;
119 |
120 | $container->bind('name', function () {
121 | return 'Taylor';
122 | });
123 |
124 | $this->assertFalse($container->exists("name"));
125 |
126 | $container->make('name');
127 |
128 | $this->assertTrue($container->exists('name'));
129 | }
130 |
131 | public function testInstance()
132 | {
133 | $container = new Container;
134 |
135 | $container->bind('name', function () {
136 | return 'Taylor';
137 | });
138 |
139 | $this->assertEquals('Taylor', $container->get('name'));
140 |
141 | $container->bind('name2', Taylor::class);
142 |
143 | $object = new stdClass();
144 |
145 | $this->assertFalse($container->exists('name2'));
146 |
147 | $container->instance('name2', $object);
148 |
149 | $this->assertTrue($container->exists('name2'));
150 |
151 | $this->assertTrue($container->exists(Taylor::class));
152 |
153 | $this->assertEquals($object, $container->make(Taylor::class));
154 |
155 | unset($container->name1);
156 |
157 | $this->assertFalse($container->exists('name1'));
158 |
159 | $container->delete('name2');
160 |
161 | $this->assertFalse($container->exists('name2'));
162 |
163 | foreach ($container as $class => $instance) {
164 |
165 | }
166 | }
167 |
168 | public function testSelf()
169 | {
170 | $container = new Container;
171 |
172 | $taylor = new Taylor('test');
173 |
174 | $container->invoke([Taylor::class, 'make'], [$taylor]);
175 | }
176 |
177 | public function testBind()
178 | {
179 | $container = new Container;
180 |
181 | $object = new stdClass();
182 |
183 | $container->bind(['name' => Taylor::class]);
184 |
185 | $container->bind('name2', $object);
186 |
187 | $container->bind('name3', Taylor::class);
188 |
189 | $container->name4 = $object;
190 |
191 | $container['name5'] = $object;
192 |
193 | $this->assertTrue(isset($container->name4));
194 |
195 | $this->assertTrue(isset($container['name5']));
196 |
197 | $this->assertInstanceOf(Taylor::class, $container->get('name'));
198 |
199 | $this->assertSame($object, $container->get('name2'));
200 |
201 | $this->assertSame($object, $container->name4);
202 |
203 | $this->assertSame($object, $container['name5']);
204 |
205 | $this->assertInstanceOf(Taylor::class, $container->get('name3'));
206 |
207 | unset($container['name']);
208 |
209 | $this->assertFalse(isset($container['name']));
210 |
211 | unset($container->name3);
212 |
213 | $this->assertFalse(isset($container->name3));
214 | }
215 |
216 | public function testAutoConcreteResolution()
217 | {
218 | $container = new Container;
219 |
220 | $taylor = $container->make(Taylor::class);
221 |
222 | $this->assertInstanceOf(Taylor::class, $taylor);
223 | $this->assertSame('Taylor', $taylor->name);
224 | }
225 |
226 | public function testGetAndSetInstance()
227 | {
228 | $this->assertInstanceOf(Container::class, Container::getInstance());
229 |
230 | $object = new stdClass();
231 |
232 | Container::setInstance($object);
233 |
234 | $this->assertSame($object, Container::getInstance());
235 |
236 | Container::setInstance(function () {
237 | return $this;
238 | });
239 |
240 | $this->assertSame($this, Container::getInstance());
241 | }
242 |
243 | public function testResolving()
244 | {
245 | $container = new Container();
246 | $container->bind(Container::class, $container);
247 |
248 | $container->resolving(function (SomeClass $taylor, Container $container) {
249 | $taylor->count++;
250 | });
251 | $container->resolving(SomeClass::class, function (SomeClass $taylor, Container $container) {
252 | $taylor->count++;
253 | });
254 |
255 | /** @var SomeClass $someClass */
256 | $someClass = $container->make(SomeClass::class);
257 | $this->assertEquals(2, $someClass->count);
258 | }
259 |
260 | public function testInvokeFunctionWithoutMethodThrowsException()
261 | {
262 | $this->expectException(FuncNotFoundException::class);
263 | $this->expectExceptionMessage('function not exists: ContainerTestCallStub()');
264 | $container = new Container();
265 | $container->invokeFunction('ContainerTestCallStub', []);
266 | }
267 |
268 | public function testInvokeProtectionMethod()
269 | {
270 | $container = new Container();
271 | $this->assertTrue($container->invokeMethod([Taylor::class, 'protectionFun'], [], true));
272 | }
273 |
274 | public function testInvoke()
275 | {
276 | $container = new Container();
277 |
278 | Container::setInstance($container);
279 |
280 | $container->bind(Container::class, $container);
281 |
282 | $stub = $this->createMock(Taylor::class);
283 |
284 | $stub->expects($this->once())->method('some')->with($container)->will($this->returnSelf());
285 |
286 | $container->invokeMethod([$stub, 'some']);
287 |
288 | $this->assertEquals('48', $container->invoke('ord', ['0']));
289 |
290 | $this->assertSame($container, $container->invoke(Taylor::class . '::test', []));
291 |
292 | $this->assertSame($container, $container->invokeMethod(Taylor::class . '::test'));
293 |
294 | $reflect = new ReflectionMethod($container, 'exists');
295 |
296 | $this->assertTrue($container->invokeReflectMethod($container, $reflect, [Container::class]));
297 |
298 | $this->assertSame($container, $container->invoke(function (Container $container) {
299 | return $container;
300 | }));
301 |
302 | $this->assertSame($container, $container->invoke(Taylor::class . '::test'));
303 |
304 | $object = $container->invokeClass(SomeClass::class);
305 | $this->assertInstanceOf(SomeClass::class, $object);
306 | $this->assertSame($container, $object->container);
307 |
308 | $stdClass = new stdClass();
309 |
310 | $container->invoke(function (Container $container, stdClass $stdObject, $key1, $lowKey, $key2 = 'default') use ($stdClass) {
311 | $this->assertEquals('value1', $key1);
312 | $this->assertEquals('default', $key2);
313 | $this->assertEquals('value2', $lowKey);
314 | $this->assertSame($stdClass, $stdObject);
315 | return $container;
316 | }, ['some' => $stdClass, 'key1' => 'value1', 'low_key' => 'value2']);
317 | }
318 |
319 | public function testInvokeMethodNotExists()
320 | {
321 | $container = $this->resolveContainer();
322 | $this->expectException(FuncNotFoundException::class);
323 |
324 | $container->invokeMethod([SomeClass::class, 'any']);
325 | }
326 |
327 | public function testInvokeClassNotExists()
328 | {
329 | $container = new Container();
330 |
331 | Container::setInstance($container);
332 |
333 | $container->bind(Container::class, $container);
334 |
335 | $this->expectExceptionObject(new ClassNotFoundException('class not exists: SomeClass'));
336 |
337 | $container->invokeClass('SomeClass');
338 | }
339 |
340 | public function testInvokeWithDefaultValues()
341 | {
342 | $container = $this->resolveContainer();
343 |
344 | $class = $container->invokeClass(WithDefaultValues::class);
345 | $this->assertSame(null, $class->container);
346 |
347 | $container->bind(Container::class, $container);
348 | $bound = $container->invokeClass(WithDefaultValues::class);
349 | $this->assertSame($container, $bound->container);
350 |
351 | $this->assertSame(null, $container->invokeMethod(WithDefaultValues::class . '::classExistsButCannotBeInjected'));
352 | }
353 |
354 | protected function resolveContainer()
355 | {
356 | $container = new Container();
357 |
358 | Container::setInstance($container);
359 | return $container;
360 | }
361 | }
362 |
--------------------------------------------------------------------------------
/tests/bootstrap.php:
--------------------------------------------------------------------------------
1 |