| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- namespace App\Module\Test\Providers;
- use App\Module\Test\Events\TestEvent;
- use App\Module\Test\Listeners\TestEventListener;
- use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
- class TestServiceProvider extends ServiceProvider
- {
- /**
- * 事件到监听器的映射
- *
- * @var array<class-string, array<int, class-string>>
- */
- 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}";
- }
- }
|