我应该在哪里放置模型保存事件侦听器在 laravel 5.1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31313019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where should I put model saving event listener in laravel 5.1
提问by refear99
The Laravel docs say I should put the model events in the EventServiceProvider boot()
method like this.
Laravel 文档说我应该EventServiceProvider boot()
像这样将模型事件放在方法中。
public function boot(DispatcherContract $events)
{
Raisefund::saved(function ($project) {
//do something
});
}
But I have many models that I want to listen to.
So I was wondering if it is the right way to put it all in the EventServiceProvider
.
但是我有很多模型想听。
所以我想知道将它全部放入EventServiceProvider
.
回答by jedrzej.kurylo
You can register listener callbacks in your models bootmethod, e.g.:
您可以在模型引导方法中注册侦听器回调,例如:
class User extends Eloquent {
protected static function boot() {
parent::boot();
static::deleting(function ($user) {
// deleting listener logic
});
static::saving(function ($user) {
// saving listener logic
});
}
}
回答by Szenis
Yes that's correct, the EventServiceProvider
is the best place for it.
是的,这EventServiceProvider
是正确的,这是最好的地方。
However you can create Observers to keep it clean. I will give you a quick example.
但是,您可以创建观察者以保持清洁。我会给你一个简单的例子。
EventServiceProvider
事件服务提供者
<?php
namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use App\Models\Users;
use App\Observers\UserObserver;
/**
* Event service provider class
*/
class EventServiceProvider extends ServiceProvider
{
/**
* Boot function
*
* @param DispatcherContract $events
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
Users::observe(new UserObserver());
}
}
UserObserver
用户观察者
<?php
namespace App\Observers;
/**
* Observes the Users model
*/
class UserObserver
{
/**
* Function will be triggerd when a user is updated
*
* @param Users $model
*/
public function updated($model)
{
}
}
The Observer
will be the place where the saved
, updated
, created
, etc.. functions will be executed.
More information about Observers: http://laravel.com/docs/5.0/eloquent#model-observers
在Observer
会里的地方saved
,updated
,created
,等功能将被执行。
关于观察者的更多信息:http: //laravel.com/docs/5.0/eloquent#model-observers