Laravel事件和监听器使用
19-07-19 11:45
字数 250
阅读 2038
已编辑
文档: https://learnku.com/docs/laravel/5.8/events/3917
1. 注册事件和监听器
在App\Providers\EventServiceProvider
的listen
属性中添加事件和监听器
protected $listen = [
// 后台管理员操作生成日志
'App\Events\AdminOperated' => [
'App\Listeners\PutOperationLog',
],
];
2. 生成事件和监听器
php artisan event:generate
3. 定义事件
<?php
namespace App\Events;
use App\Models\ArticleComment;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
class AdminOperated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* @var array
*/
public $log;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($log)
{
$this->log = $log;
}
}
4. 定义监听器
<?php
namespace App\Listeners;
use App\Events\AdminOperated;
use App\Models\OperationLog;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;
class PutOperationLog implements ShouldQueue
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param AdminOperated $event
* @return void
*/
public function handle(AdminOperated $event)
{
try {
OperationLog::query()->create($event->log);
} catch (QueryException $e) {
Log::error(sprintf('管理员操作日志写入失败: %s', $e->getMessage()));
}
}
}
5. 分发事件
<?php
namespace App\Http\Controllers\Admin;
use App\Events\AdminOperated;
use App\Models\AdminAction;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
class AdminActionController extends Controller
{
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return array
*/
public function destroy($id)
{
try {
AdminAction::destroy($id);
} catch (QueryException $e) {
Log::error($e->getMessage());
return $this->json_return(parent::DB_ERROR);
}
$log = sprintf('删除权限: %s', AdminAction::query()->find($id)->name);
event(new AdminOperated($log));
return $this->json_return();
}
}
2人点赞>
请登录后发表评论
相关推荐
文章归档
最新文章
最受欢迎
10-30 12:05
23-09-27 17:00
23-09-03 10:57
23-09-02 17:11
3 评论
3 评论
2 评论
更新了排版