首页 > 解决方案 > 使用观察者创建新记录是否合乎逻辑?

问题描述

我正在尝试做一个“通知”系统,我得到了一些条件,当这些条件被触发时,我会在“通知”表中创建一个通知记录。

例如; 当我的产品数量低于“关键库存水平”时,它将在“通知”表中创建新记录。

我将使用下面的代码:

Product.php 模型:

use App\Traits\RecordSignature;
class Product extends Model
{
    use RecordSignature, TrimScalarValues;
    ....

记录签名.php

namespace App\Traits;

use app\Observers\ModelSignature;

trait RecordSignature
{
    
    public static function bootObservantTrait()
    {
        static::observe(new ModelSignature);
    }
}

模型签名.php

namespace App\Observers;

class ModelSignature {

    protected $userID;

    public function __construct($userID){
        $this->userID =  Auth::id();
    }


    public function created($model)
    {
        if($model->critical > $model->quantity){
          $notif = new Notification();
          $notif->message = 'your product is below the critical stock';
          $notif->save();
        }
    }

}

这是实现它的好方法吗?(我将为更多的表格制作更多的观察者)或者这些条件检查是否有任何“更好的方法”?

标签: laravel

解决方案


推荐阅读