TestServiceProvider.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Module\Test\Providers;
  3. use App\Module\Test\Events\TestEvent;
  4. use App\Module\Test\Listeners\TestEventListener;
  5. use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
  6. class TestServiceProvider extends ServiceProvider
  7. {
  8. /**
  9. * 事件到监听器的映射
  10. *
  11. * @var array<class-string, array<int, class-string>>
  12. */
  13. protected $listen = [
  14. TestEvent::class => [
  15. TestEventListener::class,
  16. ],
  17. ];
  18. /**
  19. * 注册任何事件监听器
  20. */
  21. public function boot(): void
  22. {
  23. parent::boot();
  24. // 注册命令
  25. $this->registerCommands();
  26. }
  27. /**
  28. * 注册Test模块的命令 - 自动发现机制
  29. */
  30. protected function registerCommands(): void
  31. {
  32. if ($this->app->runningInConsole()) {
  33. // 自动发现并注册Test模块Commands目录下的所有命令
  34. $this->loadCommandsFrom(__DIR__ . '/../Commands');
  35. }
  36. }
  37. /**
  38. * 自动加载指定目录下的所有命令类
  39. *
  40. * @param string $path 命令目录路径
  41. */
  42. protected function loadCommandsFrom(string $path): void
  43. {
  44. if (!is_dir($path)) {
  45. return;
  46. }
  47. // 获取目录下所有PHP文件
  48. $files = glob($path . '/*.php');
  49. foreach ($files as $file) {
  50. // 从文件路径推导类名
  51. $className = $this->getClassNameFromFile($file);
  52. if ($className && class_exists($className)) {
  53. // 检查是否是Command的子类且不是抽象类
  54. $reflection = new \ReflectionClass($className);
  55. if ($reflection->isSubclassOf(\Illuminate\Console\Command::class) &&
  56. !$reflection->isAbstract()) {
  57. $this->commands([$className]);
  58. }
  59. }
  60. }
  61. }
  62. /**
  63. * 从文件路径推导完整的类名
  64. *
  65. * @param string $filePath 文件路径
  66. * @return string|null 类名
  67. */
  68. protected function getClassNameFromFile(string $filePath): ?string
  69. {
  70. $fileName = basename($filePath, '.php');
  71. return "App\\Module\\Test\\Commands\\{$fileName}";
  72. }
  73. }