最近,我在 Laravel 5 的一个项目中遇到了同样的问题,我必须记录所有模型事件。我决定使用.我创建了Trait,并简单地用于所有需要记录的模型类。我将根据您的需要更改它,如下所示。Traits
ModelEventLogger
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;
/**
* Class ModelEventThrower
* @package App\Traits
*
* Automatically throw Add, Update, Delete events of Model.
*/
trait ModelEventThrower {
/**
* Automatically boot with Model, and register Events handler.
*/
protected static function bootModelEventThrower()
{
foreach (static::getModelEvents() as $eventName) {
static::$eventName(function (Model $model) use ($eventName) {
try {
$reflect = new \ReflectionClass($model);
Event::fire(strtolower($reflect->getShortName()).'.'.$eventName, $model);
} catch (\Exception $e) {
return true;
}
});
}
}
/**
* Set the default events to be recorded if the $recordEvents
* property does not exist on the model.
*
* @return array
*/
protected static function getModelEvents()
{
if (isset(static::$recordEvents)) {
return static::$recordEvents;
}
return [
'created',
'updated',
'deleted',
];
}
}
现在,您可以在要为其引发事件的任何模型中使用此特征。在模型中,Article
<?php namespace App;
use App\Traits\ModelEventThrower;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
use ModelEventThrower;
//Just in case you want specific events to be fired for Article model
//uncomment following line of code
// protected static $recordEvents = ['created'];
}
现在,在 方法中注册 的事件处理程序。app/Providers/EventServiceProvider.php
boot()
Article
public function boot(DispatcherContract $events)
{
parent::boot($events);
$events->subscribe('App\Handlers\Events\ArticleEventHandler');
}
现在在目录下创建类,如下所示,ArticleEventHandler
app/Handlers/Events
<?php namespace App\Handlers\Events;
use App\Article;
class ArticleEventHandler{
/**
* Create the event handler.
*
* @return \App\Handlers\Events\ArticleEventHandler
*/
public function __construct()
{
//
}
/**
* Handle article.created event
*/
public function created(Article $article)
{
//Implement logic
}
/**
* Handle article.updated event
*/
public function updated(Article $article)
{
//Implement logic
}
/**
* Handle article.deleted event
*/
public function deleted(Article $article)
{
//Implement logic
}
/**
* @param $events
*/
public function subscribe($events)
{
$events->listen('article.created',
'App\Handlers\Events\ArticleEventHandler@created');
$events->listen('article.updated',
'App\Handlers\Events\ArticleEventHandler@updated');
$events->listen('article.deleted',
'App\Handlers\Events\ArticleEventHandler@deleted');
}
}
从不同的答案中,从不同的用户那里可以看出,处理模型事件的方法不止一种。还有自定义事件,可以在事件文件夹中创建,可以在Handler文件夹中处理,并且可以从不同位置调度。我希望它有帮助。