Laravel框架Event事件实现

1、注册事件以及监听器

  • 首先我们在app/Providers/EventServiceProvider.php文件中定义事件与监听器的映射关系,如下:
/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    // 管理员登录后台记录最后登录时间、IP以及累计登录次数
    'App\Events\Admin\AdminLoginEvent' => [
        'App\Listeners\Admin\AdminLoginListener',
    ]
];
  • 在项目的根目录执行如下命令
php artisan event:generate
  • 该命令执行成功后,会在app\Events\Admin和app\Listeners\Admin文件夹下分别生成AdminLoginEvent.php和AdminLoginListener.php文件,如图:

2、定义事件

<?php

namespace App\Events\Admin;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class AdminLoginEvent {
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $adminId;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($adminId = 0) {
        $this->adminId = $adminId;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn() {
        return new PrivateChannel('channel-name');
    }
}

3、定义监听器

<?php

namespace App\Listeners\Admin;

use App\Events\Admin\AdminLoginEvent;

class AdminLoginListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AdminLoginEvent  $event
     * @return Bool
     */
    public function handle(AdminLoginEvent $event)
    {
        $adminId = $event->adminId;
        if (!$adminId){
            return false;
        }

        // todo 更新管理员的最后登录时间、IP以及累计登录次数

        return true;
    }
}

4、触发事件

<?php

namespace App\OpenApi\Controllers\API\Test;

use App\Events\Admin\AdminLoginEvent;
use App\OpenApi\Controllers\BaseController;
use Illuminate\Http\Request;

class TestController extends BaseController {

    public function index(Request $request) {
        event(new AdminLoginEvent($request->adminId));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值