Skip to content

Commit 6b24293

Browse files
committed
支持闭包
1 parent 9ce708e commit 6b24293

File tree

3 files changed

+29
-13
lines changed

3 files changed

+29
-13
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.Ds_Store

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,23 @@ class Replace implements TemplateMagicHandleInterface
3232

3333
### 配置
3434
`config/template_magic.php`
35+
3536
```php
3637
use app\Replace;
3738

3839
return [
3940
'handle' => Replace::class
4041
]
42+
```
43+
44+
支持闭包
45+
```php
46+
use xiaodi\Contracts\TemplateMagicReplaceInterface;
47+
48+
return [
49+
'handle' => function (TemplateMagicReplaceInterface $handle) {
50+
$handle->head('<link rel="stylesheet" href="https://static.kodcloud.com/index/js/lib/bootstrap-3.3.7/css/bootstrap.min.css">');
51+
}
52+
];
53+
4154
```

src/TemplateMagicService.php

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66

77
use \Closure;
88
use \Exception;
9+
use \ReflectionClass;
910
use think\Service;
1011
use xiaodi\Contracts\TemplateMagicHandleInterface;
12+
use think\Container;
1113

1214
class TemplateMagicService extends Service
1315
{
@@ -28,22 +30,22 @@ public function register()
2830
*
2931
* @return void
3032
*/
31-
public function boot()
33+
public function boot(TemplateMagic $magic)
3234
{
3335
$config = config('template_magic');
34-
if ($config['handle']) {
35-
if ($config['handle'] instanceof Closure) {
36-
// TODO
37-
} else {
38-
$handle = new $config['handle'];
39-
40-
if (false === $handle instanceof TemplateMagicHandleInterface) {
41-
throw new Exception('class '.$config['handle'] . ' is not instanceof \xiaodi\Contracts\TemplateMagicHandleInterface');
42-
}
43-
44-
$magic = new TemplateMagic();
45-
$handle->handle($magic);
36+
$handle = $config['handle'];
37+
38+
if (false == empty($handle)) {
39+
if ($handle instanceof Closure) {
40+
return Container::getInstance()->invokeFunction($handle, [$magic]);
41+
}
42+
43+
$obj = new ReflectionClass($handle);
44+
if (false === $obj->implementsInterface(TemplateMagicHandleInterface::class)) {
45+
throw new Exception('class ' . $handle . ' is not instanceof \xiaodi\Contracts\TemplateMagicHandleInterface');
4646
}
47+
48+
Container::getInstance()->invokeClass($handle)->handle($magic);
4749
}
4850
}
4951
}

0 commit comments

Comments
 (0)