Laravel 4 如何监听模型事件? [英] Laravel 4 how to listen to a model event?

查看:27
本文介绍了Laravel 4 如何监听模型事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to have an event listener binding with a model event updating.
For instance, after a post is updated, there's an alert notifying the updated post title, how to write an event listener to have the notifying (with the post title value passing to the listener?

推荐答案

文档简要提到了 Model Events.它们在模型上都有一个辅助函数,因此您无需知道它们是如何构建的.

The documentation briefly mentions Model Events. They've all got a helper function on the model so you don't need to know how they're constructed.

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

Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods: creating, created, updating, updated, saving, saved, deleting, deleted. If false is returned from the creating, updating, saving or deleting events, the action will be cancelled.

<小时>

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 那么它们将取消操作.

If you return false from the functions marked * then they will cancel the operation.

更多细节,你可以查看Illuminate/Database/Eloquent/Model,你会在那里找到所有的事件,寻找 static::registerModelEvent$this->fireModelEvent 的使用.

For more detail, you can look through Illuminate/Database/Eloquent/Model and you will find all the events in there, look for uses of static::registerModelEvent and $this->fireModelEvent.

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

Events on Eloquent models are structured as eloquent.{$event}: {$class} and pass the model instance as a parameter.

这篇关于Laravel 4 如何监听模型事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆