【问题标题】:Find which model method is triggering the Event查找触发事件的模型方法
【发布时间】:2022-01-15 15:20:53
【问题描述】:

我正在使用 Laravel 的 Event & Listener 功能来检测以下模型操作并触发一些应用程序逻辑。

应用程序/模型/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
];

应用程序/事件/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;
}

是否可以检测到触发事件的模型操作?我希望能够知道触发事件的记录是否已创建/更新/删除。知道我正在使用软删除来检查记录是否被删除,但我如何知道记录是否已更新或创建?

【问题讨论】:

  • 你为什么不创建3个类?它们都可以从MealFood 继承,然后您可以通过检查哪个类正在运行来确定触发了哪个事件。
  • 不确定我是否理解。 3节课干什么用的?扩展模型?

标签: laravel laravel-events laravel-models


【解决方案1】:

创建 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 抽象化,因为您永远不需要直接创建它的实例。

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 2016-09-11
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多