gpt4 book ai didi

php - Laravel 模型事件的多个监听器

转载 作者:行者123 更新时间:2023-12-03 23:00:52 26 4
gpt4 key购买 nike

我有一个名为 RecordsUserActivity 的特征,当用户创建、更新或删除使用此特征的内容时,它基本上会在事件表中创建一条记录。这是代码:

trait RecordsUserActivity
{
protected static function boot()
{
parent::boot();
foreach (static::getModelEvents() as $event) {
static::$event(function ($model) use ($event) {
$model->addActivity($event);
});
}
}

protected function addActivity($event)
{
$newActivity = [
'subject_id' => $this->id,
'subject_type' => get_class($this),
'action' => $event,
'user_id' => (Auth::id()) ?? null,
];

if ($event == 'updated') {
$newActivity['data'] = json_encode($this->getDirty());
}

UserActivity::create($newActivity);
}

protected static function getModelEvents()
{
if (isset(static::$recordEvents)) {
return static::$recordEvents;
}

return ['created', 'deleted', 'updated'];
}
}

然后我有另一个特征,它记录使用它的模型中的属性变化。这是代码:
trait RecordsPropertyChangelog
{
protected static function boot()
{
parent::boot();

static::updated(function ($model){
$model->addPropertiesChangelog();
});
}

protected function addPropertiesChangelog()
{
$dirty = $this->getDirty();
foreach ($dirty as $field => $newData) {
$oldData = $this->getOriginal($field);
$this->addPropertyChangelog($field,$oldData,$newData);
}
}

protected function addPropertyChangelog($fieldName,$oldValue,$newValue)
{
PropertyChangelog::create([
'resource_id' => $this->id,
'resource_type' => get_class($this),
'property' => $fieldName,
'from_value' => $oldValue,
'to_value' => $newValue,
'data' => '{}',
]);
}

}

当我在模型中包含这两个特征并进行更新时,就会出现问题,这两个更新的模型事件都会发生某种冲突。有什么方法可以解决这个问题还是我应该找到另一种解决方案?

最佳答案

如果您尝试在同一模型上使用这两个特征,您应该会收到一条错误消息,指出 Trait method boot has not been applied, because there are collisions with other trait methods... .

无论如何,您不希望您的特征定义 boot()方法。 Laravel 的 Model如果您有一个需要 Hook 到 boot 的特征,则有一个特殊约定方法。基本上,在你的 trait 中,以 boot{traitName} 的格式定义一个方法。 .此外,删除对 parent::boot() 的调用。在这两种方法中。 boot()基于 Model 的方法当 Model 时,将调用符合此格式的方法已启动。

因此,您的特征应如下所示:

trait RecordsUserActivity
{
protected static function bootRecordsUserActivity()
{
foreach (static::getModelEvents() as $event) {
static::$event(function ($model) use ($event) {
$model->addActivity($event);
});
}
}

//...
}

trait RecordsPropertyChangelog
{
protected static function bootRecordsPropertyChangelog()
{
static::updated(function ($model) {
$model->addPropertiesChangelog();
});
}

//...
}

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

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