Laravel事件和监听器使用

19-07-19 11:45 字数 250 阅读 2038 已编辑

文档: https://learnku.com/docs/laravel/5.8/events/3917

1. 注册事件和监听器App\Providers\EventServiceProviderlisten属性中添加事件和监听器

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人点赞>
关注 收藏 改进 举报
1 条评论
排序方式 时间 投票
Up骚年

更新了排版

请登录后发表评论