Jac*_*otK 15 laravel eloquent laravel-4
我希望有一个事件监听器绑定模型事件updating.
例如,在帖子更新后,会有一条警告通知更新的帖子标题,如何编写一个事件监听器来通知(帖子标题值传递给听众?
Rex*_*der 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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
@ phill-sparks在其答案中共享的事件列表可以应用于单个模块.
Phi*_*rks 18
文档简要提到了模型事件.他们都在模型上有一个辅助函数,所以你不需要知道它们是如何构造的.
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) { });
Run Code Online (Sandbox Code Playgroud)
如果false从标记的功能返回,*则它们将取消操作.
欲了解更多的细节,你可以看看通过照亮/数据库/雄辩/型号,你会发现在那里所有的事件,寻找的用途static::registerModelEvent和$this->fireModelEvent.
Eloquent模型上的事件被构造为eloquent.{$event}: {$class}并将模型实例作为参数传递.
我坚持这个因为我假设订阅默认模型事件,比如Event:listen('user.created',函数($ 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)....
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17893 次 |
| 最近记录: |