So according to the laravel event doc, when defining listeners, it can receive the event instance in their handle method and perform any logic necessary:
public function handle(FoodWasPurchased $event)
因此,如果我的FoodWasPurchased事件定义如下(假定设置了EventServiceProvider):
public function __construct(Food $food)
{
$this->food = $food;
}
I could access the $food in event from listener by doing:
$event->food->doSomething();
But now my question is what if a listener listen to multiple events?
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...
}
我相信有更好的办法.
Or the best practice is ensure that one listener only listens to one single event ?