事件
作用
- 核心思想:解耦
- 控制器 / 服务只负责「触发事件」,不关心后续执行什么逻辑;监听者单独处理业务。
- 比如:用户注册成功 → 触发 UserRegistered 事件;
- 监听者可以独立实现:发送欢迎短信、记录日志、赠送积分,不用把一堆代码堆在注册逻辑里。
流程
- 事件 Event:载体,存放数据(如用户信息)
- 监听器 Listener:事件触发后执行的业务
- 分发(触发):event(new UserRegistered($user))
- 两种运行模式:同步(当前请求阻塞) / 异步队列(推荐,不阻塞接口)
案例
创建事件
bash
# 生成 app/Events/AdminLogin.php 事件类
php artisan make:event AdminLoginEvent
# 生成 app/Listeners/WelcomeSmsListener.php 监听器
php artisan make:listener WelcomeSmsListener --event AdminLoginEvent- 事件类, 只负责收集数据, 不负责执行业务
php
<?php
namespace App\Events;
use App\Models\Admin;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class AdminLoginEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*/
public function __construct(public Admin $admin)
{
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, Channel>
*/
public function broadcastOn(): array
{
return [
new PrivateChannel('channel-name'),
];
}
}- 监听器, 只负责执行业务, 不负责收集数据
php
<?php
namespace App\Listeners;
use App\Events\AdminLoginEvent;
use Illuminate\Support\Facades\Log;
class WelcomeSmsListener
{
/**
* Create the event listener.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*/
public function handle(AdminLoginEvent $event): void
{
$admin = $event->admin;
$phone = $admin->phone;
$message = "欢迎您,您的手机号为:$phone";
$this->sendSms($phone, $message);
}
private function sendSms($phone, $message)
{
// TODO: 发送短信
// 暂时 使用 log 记录 方便测试
Log::info("发送短信:$message 给 $phone");
}
}监听事件
- 注册服务, 专门负责事件监听器
bash
php artisan make:provider EventServiceProviderphp
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Events\AdminLoginEvent;
use App\Listeners\WelcomeSmsListener;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
// 用户注册事件
AdminLoginEvent::class => [
// 发送欢迎短信
WelcomeSmsListener::class,
],
];
/**
* Register services.
*/
public function register(): void
{
//
}
/**
* Bootstrap services.
*/
public function boot(): void
{
//
}
}触发事件
php
use App\Events\AdminLoginEvent;
public function register()
{
$user = User::create(['name'=>'test','phone'=>'13800138000']);
// 触发注册事件
AdminLoginEvent::dispatch($user);
return '注册成功';
}异步队列
- 配置
.env
text
QUEUE_CONNECTION=redis- 监听器, 实现
ShouldQueue接口, 配置队列连接
php
<?php
namespace App\Listeners;
use App\Events\AdminLoginEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
# 继承 ShouldQueue 接口
class WelcomeSmsListener implements ShouldQueue
{
/**
* 任务最大尝试次数
*/
public int $tries = 3;
/**
* 每次重试延迟(秒)
*/
public int $backoff = 5;
/**
* 指定队列名称(可选,区分业务队列)
*/
public string $queue = 'sms';
/**
* Create the event listener.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*/
public function handle(AdminLoginEvent $event): void
{
$admin = $event->admin;
$phone = $admin->phone;
$message = "欢迎您,您的手机号为:$phone";
$this->sendSms($phone, $message);
// 模拟异常测试:放开下面代码观察失败重试
// throw new \RuntimeException("短信网关暂时不可用");
}
private function sendSms($phone, $message): void
{
// TODO: 发送短信
// 暂时 使用 log 记录 方便测试
Log::info("发送短信:$message 给 $phone");
}
/**
* 任务多次失败最终执行的回调(可选)
*/
public function failed(AdminLoginEvent $event, \Throwable $exception): void
{
Log::error("短信发送任务最终失败", [
'admin_id' => $event->admin->id,
'error' => $exception->getMessage()
]);
}
}- 消费队列
bash
# 消费默认队列
php artisan queue:work
# 指定消费我们定义的 sms、stat 队列(优先处理)
php artisan queue:work --queue=sms,stat
# 生产守护进程(推荐)
php artisan queue:work --daemon --queue=sms,stat
# 查看失败任务
php artisan queue:failed
# 重试失败任务
php artisan queue:retry 任务ID