laravel事件监听器

在EventServiceProvide文件里注册事件和监听

protected $listen = [
        'AppEventsSendPhoneCodeEvent' => [
            'AppListenersSendPhoneCodeListener',
        ]
    ];

1.建立事件文件Events/SendPhoneCodeEvent.php

<?php
namespace AppEvents;

class SendPhoneCodeEvent
{
    use SerializesModels;

    public $data;

    /**
     * 创建一个事件实例。
     *
     * @param  AppOrder  $order
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }
}

2.建立监听文件 Listeners/SendPhoneCodeListener.php

<?php
namespace AppListeners;

use AppEventsSendPhoneCodeEvent;
use IlluminateSupportFacadesLog;

class SendPhoneCodeListener
{
    /**
     * 创建事件监听器。
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * 处理事件。
     *
     * @param  AppEventsSendPhoneCodeEvent  $event
     * @return void
     */
    public function handle(SendPhoneCodeEvent $event)
    {

        Log::info("Listener:".$event->data);
    }

    public function failed()
    {
    }
}

4.有控制器里调用事件

use AppEventsSendPhoneCodeEvent;

event(new SendPhoneCodeEvent('123456789'));
原文地址:https://www.cnblogs.com/vania/p/11865342.html