因此,我使用Laravel模型事件观察者来触发自定义事件逻辑,但它们仅接受模型作为单个参数。我想做的是调用一个自定义事件,我还可以将一些额外的参数传递给该事件,从而将其传递给Observer方法。像这样:
$this->fireModelEvent('applied', $user, $type);
然后在观察者
/**
* Listen to the applied event.
*
* @param Item $item
* @param User $user
* @param string $type
* @return void
*/
public function applied(Item $item, $user, string $type) {
Event::fire(new Applied($video, $user, $type));
}
如您所见,我对传递执行此操作的用户很感兴趣,这不一定是创建该项目的用户。我不认为临时模型属性是答案,因为我的其他事件逻辑随着作业而排队,以保持尽可能短的响应时间。任何人都对我如何扩展Laravel让我做到这一点有任何想法?
我的理论是做一个自定义特性,该特性会覆盖处理该逻辑的基本laravel模型类中的一个或多个函数。以为我在研究的过程中会发现是否还有其他人需要这样做。
Also here's the docs reference
最佳答案
我通过使用特征实现一些自定义模型功能来完成此任务。
/**
* Stores event key data
*
* @var array
*/
public $eventData = [];
/**
* Fire the given event for the model.
*
* @param string $event
* @param bool $halt
* @param array $data
* @return mixed
*/
protected function fireModelEvent($event, $halt = true, array $data = []) {
$this->eventData[$event] = $data;
return parent::fireModelEvent($event, $halt);
}
/**
* Get the event data by event
*
* @param string $event
* @return array|NULL
*/
public function getEventData(string $event) {
if (array_key_exists($event, $this->eventData)) {
return $this->eventData[$event];
}
return NULL;
}