在Laravel中,可以使用事件系统来处理事件和监听器之间的迭代问题。下面是一个解决方法的示例代码:
MyEvent
:namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MyEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
}
MyEventListener
:namespace App\Listeners;
use App\Events\MyEvent;
class MyEventListener
{
public function handle(MyEvent $event)
{
// 处理事件
}
}
EventServiceProvider
类的 listen
数组中添加以下代码:protected $listen = [
MyEvent::class => [
MyEventListener::class,
],
];
use App\Events\MyEvent;
event(new MyEvent($data));
这样,当 MyEvent
事件被触发时,Laravel 将会自动迭代并调用注册的监听器 MyEventListener
来处理事件。