查找触发事件的模型方法

Find which model method is triggering the Event

我正在使用 Laravel 的事件和侦听器功能来检测以下模型操作并触发一些应用程序逻辑。

app/models/MealFood

/**
 * The event map for the model.
 *
 * Allows for object-based events for native Eloquent events.
 *
 * @var array
 */
protected $dispatchesEvents = [
    'created'  => MealFoodEvent::class,
    'updated'  => MealFoodEvent::class,
    'deleted'  => MealFoodEvent::class
];

app/events/MealFoodEvent

public $mealFood;

/**
 * Create a new event instance.
 *
 * @param MealFood $mealFood
 */
public function __construct(MealFood $mealFood)
{
    $this->mealFood = $mealFood;
}

app/listeners/MealFoodListener

public function handle(MealFoodEvent $event)
{
    $mealFood = $event->mealFood;
}

是否可以检测是什么模型操作触发了事件?我想知道触发事件的记录是否为 created/updated/deleted。没错,我正在使用软删除来检查记录是否被删除,但我怎么知道记录是否被更新或创建?

再创建 3 个 类:

MealFoodCreatedEvent.php

class MealFoodCreatedEvent extends MealFoodEvent {}

MealFoodUpdatedEvent.php

class MealFoodUpdatedEvent extends MealFoodEvent {}

MealFoodDeletedEvent.php

class MealFoodDeletedEvent extends MealFoodEvent {}

修改您的模型:

protected $dispatchesEvents = [
    'created'  => MealFoodCreatedEvent::class,
    'updated'  => MealFoodUpdatedEvent::class,
    'deleted'  => MealFoodDeletedEvent::class
];

然后在您的事件处理程序中,您可以这样做:

public function handle(MealFoodEvent $event)
{
    $mealFood = $event->mealFood;
    if ($event instanceof MealFoodCreatedEvent) { 
       // the event was "created
    }
}

handle 的签名仍然有效,因为您的所有事件都扩展了 MealFoodEvent

您也可以将 MealFoodEvent 抽象化,因为您永远不需要直接创建它的实例。