laravel事件监听器
在EventServiceProvide文件里注册事件和监听
protected $listen = [ 'App\Events\SendPhoneCodeEvent' => [ 'App\Listeners\SendPhoneCodeListener', ] ];
1.建立事件文件Events/SendPhoneCodeEvent.php
<?php namespace App\Events; class SendPhoneCodeEvent { use SerializesModels; public $data; /** * 创建一个事件实例。 * * @param \App\Order $order * @return void */ public function __construct($data) { $this->data = $data; } }
2.建立监听文件 Listeners/SendPhoneCodeListener.php
<?php namespace App\Listeners; use App\Events\SendPhoneCodeEvent; use Illuminate\Support\Facades\Log; class SendPhoneCodeListener { /** * 创建事件监听器。 * * @return void */ public function __construct() { } /** * 处理事件。 * * @param \App\Events\SendPhoneCodeEvent $event * @return void */ public function handle(SendPhoneCodeEvent $event) { Log::info("Listener:".$event->data); } public function failed() { } }
4.有控制器里调用事件
use App\Events\SendPhoneCodeEvent; event(new SendPhoneCodeEvent('123456789'));