Laravel 文档说我应该将模型事件放在EventServiceProvider boot()
像这样的方法。
public function boot(DispatcherContract $events)
{
Raisefund::saved(function ($project) {
//do something
});
}
但我有很多我想听的模特。
所以我想知道将所有内容放入其中是否是正确的方法EventServiceProvider
.
是的,这是正确的,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());
}
}
用户观察者
<?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
将是一个地方saved
, updated
, created
等..函数将被执行。
有关观察员的更多信息:http://laravel.com/docs/5.0/eloquent#model-observers http://laravel.com/docs/5.0/eloquent#model-observers
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)