瀏覽代碼

feat(core): 添加Hook属性的控制台执行限制功能

- 在Hook属性类中新增$isConsole参数,用于标识是否仅在控制台环境下执行
- 修改HookAttributeService服务,增加对控制台环境的判断逻辑
- 新增running_in_console函数,用于检测当前运行环境是否为命令行模式
- 当Hook标记为仅控制台执行且不在控制台环境时,跳过该Hook的注册
- 完善Hook属性类的PHPDoc注释,明确参数含义和用途
runphp 3 月之前
父節點
當前提交
00b5532656
共有 3 個文件被更改,包括 20 次插入1 次删除
  1. 5 0
      src/Attribute/Hook.php
  2. 7 1
      src/Service/HookAttributeService.php
  3. 8 0
      src/functions.php

+ 5 - 0
src/Attribute/Hook.php

@@ -8,8 +8,13 @@ use Attribute;
 #[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
 class Hook
 {
+    /**
+     * @param string|array $hook  hook name
+     * @param bool $isConsole  is console
+     */
     public function __construct(
         public string|array $hook,
+        public bool $isConsole = false,
     )
     {
     }

+ 7 - 1
src/Service/HookAttributeService.php

@@ -11,6 +11,7 @@ use SixShop\Core\Contracts\ExtensionInterface;
 use think\Event;
 use think\exception\ClassNotFoundException;
 use function SixShop\Core\extension_name_list;
+use function SixShop\Core\running_in_console;
 
 readonly class HookAttributeService
 {
@@ -39,7 +40,12 @@ readonly class HookAttributeService
                 foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                     $attributes = $method->getAttributes(Hook::class);
                     foreach ($attributes as $attr) {
-                        $hookNameList = (array)$attr->newInstance()->hook;
+                        $hookInstance = $attr->newInstance();
+                        if ($hookInstance->isConsole && !running_in_console()) {
+                            // 仅执行在控制台
+                            continue;
+                        }
+                        $hookNameList = (array)$hookInstance->hook;
                         foreach ($hookNameList as $hookName) {
                             $this->event->listen($hookName, [$hookClass, $method->getName()]);
                         }

+ 8 - 0
src/functions.php

@@ -193,4 +193,12 @@ function extension_name_list(): array
 function extension_composer_info(string $extensionID): array
 {
     return CoreService::$extensionComposerMap[$extensionID];
+}
+
+/**
+ * 判断当前运行环境是否为命令行模式
+ */
+function running_in_console(): bool
+{
+    php_sapi_name() === 'cli' || php_sapi_name() === 'phpdbg';
 }