> */ protected $listen = [ TestEvent::class => [ TestEventListener::class, ], ]; /** * 注册任何事件监听器 */ public function boot(): void { parent::boot(); // 注册命令 $this->registerCommands(); } /** * 注册Test模块的命令 - 自动发现机制 */ protected function registerCommands(): void { if ($this->app->runningInConsole()) { // 自动发现并注册Test模块Commands目录下的所有命令 $this->loadCommandsFrom(__DIR__ . '/../Commands'); } } /** * 自动加载指定目录下的所有命令类 * * @param string $path 命令目录路径 */ protected function loadCommandsFrom(string $path): void { if (!is_dir($path)) { return; } // 获取目录下所有PHP文件 $files = glob($path . '/*.php'); foreach ($files as $file) { // 从文件路径推导类名 $className = $this->getClassNameFromFile($file); if ($className && class_exists($className)) { // 检查是否是Command的子类且不是抽象类 $reflection = new \ReflectionClass($className); if ($reflection->isSubclassOf(\Illuminate\Console\Command::class) && !$reflection->isAbstract()) { $this->commands([$className]); } } } } /** * 从文件路径推导完整的类名 * * @param string $filePath 文件路径 * @return string|null 类名 */ protected function getClassNameFromFile(string $filePath): ?string { $fileName = basename($filePath, '.php'); return "App\\Module\\Test\\Commands\\{$fileName}"; } }