gpt4 book ai didi

events - Laravel 监听器监听多个事件

转载 作者:行者123 更新时间:2023-12-03 21:09:58 25 4
gpt4 key购买 nike

所以根据laravel事件doc , 在定义监听器时,它可以在其 handle 方法中接收事件实例并执行任何必要的逻辑:

public function handle(FoodWasPurchased $event)

所以如果我的 FoodWasPurched 事件定义如下(假设设置了 EventServiceProvider):
public function __construct(Food $food)
{
$this->food = $food;
}

我可以通过执行以下操作从监听器访问事件中的 $food:
$event->food->doSomething();

但现在我的问题是,如果一个听众监听多个事件呢?
Event FoodWasPurchased -> Listener Bill
Event DrinksWasPurchased -> Listener Bill

我现在所做的是我没有在监听器句柄方法中指定事件实例:
public function handle($event)

稍后我可以使用 if 条件来检查 $event 中收到的内容:
if (isset($event->food)) {

// Do something...

} elseif (isset($event->drinks)) {

// Do something else...

}

我相信有更好的方法。

或者最好的做法是确保一个听众只听一个事件?

最佳答案

您可以使用 Event Subscribers 监听多个事件它们位于 Listeners 文件夹中,但能够监听多个事件。

<?php

namespace App\Listeners;

class UserEventListener{
/**
* Handle user login events.
*/
public function onUserLogin($event) {}

/**
* Handle user logout events.
*/
public function onUserLogout($event) {}

/**
* Register the listeners for the subscriber.
*
* @param Illuminate\Events\Dispatcher $events
* @return array
*/
public function subscribe($events){
$events->listen(
'App\Events\UserLoggedIn',
'App\Listeners\UserEventListener@onUserLogin'
);

$events->listen(
'App\Events\UserLoggedOut',
'App\Listeners\UserEventListener@onUserLogout'
);
}

}

关于events - Laravel 监听器监听多个事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31345686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com