15

我想要一个与模型事件绑定的事件侦听器updating
例如,在帖子更新后,有一个警报通知更新的帖子标题,如何编写事件侦听器以进行通知(将帖子标题值传递给侦听器?

4

4 回答 4

36

这篇文章: http ://driesvints.com/blog/using-laravel-4-model-events/

向您展示如何使用模型内的“boot()”静态函数设置事件侦听器:

class Post extends eloquent {
    public static function boot()
    {
        parent::boot();

        static::creating(function($post)
        {
            $post->created_by = Auth::user()->id;
            $post->updated_by = Auth::user()->id;
        });

        static::updating(function($post)
        {
            $post->updated_by = Auth::user()->id;
        });
    }
}

@phill-sparks 在他的回答中分享的事件列表可以应用于各个模块。

于 2013-08-06T15:34:51.823 回答
18

该文档简要提到了Model Events。它们在模型上都有一个辅助函数,所以你不需要知道它们是如何构造的。

Eloquent 模型触发多个事件,允许您使用以下方法连接到模型生命周期中的各个点:创建、创建、更新、更新、保存、保存、删除、删除。如果创建、更新、保存或删除事件返回 false,则该操作将被取消。


Project::creating(function($project) { }); // *
Project::created(function($project) { });
Project::updating(function($project) { }); // *
Project::updated(function($project) { });
Project::saving(function($project) { });  // *
Project::saved(function($project) { });
Project::deleting(function($project) { }); // *
Project::deleted(function($project) { });

如果您false从标记的功能返回,*那么它们将取消操作。


有关更多详细信息,您可以查看Illuminate/Database/Eloquent/Model并在其中找到所有事件,查找 和 的static::registerModelEvent用法$this->fireModelEvent

Eloquent 模型上的事件被构造为eloquent.{$event}: {$class}并将模型实例作为参数传递。

于 2013-05-26T10:57:41.190 回答
7

我之所以坚持这一点,是因为我认为订阅像 Event:listen('user.created',function($user) 这样的默认模型事件会起作用(正如我在评论中所说)。到目前为止,我已经看到这些选项起作用在默认模型用户创建事件的示例中:

//This will work in general, but not in the start.php file
User::created(function($user).... 
//this will work in the start.php file
Event::listen('eloquent.created: User', function($user).... 
于 2014-04-21T19:24:48.280 回答
0
Event::listen('eloquent.created: ModelName', function(ModelName $model)   {
    //...
})
于 2014-07-23T20:16:29.190 回答