在 Laravel 11 之前,我曾经将监听器绑定到
App\Providers\EventServiceProvider
提供者类中的事件,例如:
<?php
namespace App\Providers;
use App\Events\MyEvent;
use App\Listeners\MyListener;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Http\Client\Events\ResponseReceived;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
MyEvent::class => [
MyListener::class
]
];
}
在 Laravel 11 中,根本不需要这种绑定,因为 Laravel 自动发现功能会自动从
app/Listeners
目录中发现监听器。我如何指示 Laravel 自动发现来自不同目录的侦听器,例如 app/Domain/Listeners
?
从 Laravel 11 开始,您可以在
withEvents()
文件中调用 bootstrap/app.php
方法来指示框架自动发现一个或多个目录中的侦听器。
此方法采用一系列路径,用于自动发现侦听器,例如这里我们告诉 Laravel 自动发现
app/Domain/Listeners
目录中的所有侦听器:
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
channels: __DIR__.'/../routes/channels.php',
health: '/up',
)->withEvents(discover: [
app_path('Domain/Listeners')
])->create();
此处的文档中提到了这一点:https://laravel.com/docs/11.x/events#event-discovery