laravel 模型观察器

模型观察器

  • 对模型的生命周期内的多个时间点进行监控,分别有 ~ing 和 ~ed 事件
  • 每个监控方法接收 model 作为唯一参数

使用观察器

  • 创建观察器文件,一个普通类,不需要继承什么
  • 针对需要的事件,编写对应的 ~ing 或 ~ed 方法,方法接收 model 作为唯一参数
  • 在 AppServiceProvider 中注册

    // 在 boot 方法中
    
    YourModel::observe(YourModelObserver::class);

例子:需求,话题内容添加时提取话题的摘录

excerpt 字段存储的是话题的摘录

当一个新模型被初次保存将会触发 creating 以及 created 事件。如果一个模型已经存在于数据库且调用了 save 方法,将会触发 updating 和 updated 事件。在这两种情况下都会触发 saving 和 saved 事件。

在 AppServiceProvider 中注册

观察器:

app/helpers.php

function make_excerpt($value, $length = 200)
{
    $excerpt = trim(preg_replace('/
|
|
+/', ' ', strip_tags($value)));
    return str_limit($excerpt, $length);
}

也可以直接这样用:

https://learnku.com/articles/6657/model-events-and-observer-in-laravel



原文地址:https://www.cnblogs.com/sgm4231/p/11050391.html