下面由laravel教程欄目給大家介紹關(guān)于laravel事件系統(tǒng)的運(yùn)行原理,希望對(duì)大家有所幫助!
在 EventServiceProvider 里注冊(cè)(app/Providers/EventServiceProvider.php)
protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], 'AppEventsTest' => [ 'AppListenersEventListener', ], ];
使用命令行來(lái)生成事件與監(jiān)聽(tīng)器
$ php artisan event:generate
此時(shí)將生成兩個(gè)文件
1、App/Events/Test.php(事件)
編輯事件
<?php namespace AppEvents;use AppModelsUser;use IlluminateBroadcastingChannel;use IlluminateBroadcastingInteractsWithSockets;use IlluminateBroadcastingPresenceChannel;use IlluminateBroadcastingPrivateChannel;use IlluminateContractsBroadcastingShouldBroadcast;use IlluminateFoundationEventsDispatchable;use IlluminateQueueSerializesModels;class Test{ use Dispatchable, InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct($id) { echo '觸發(fā)事件成功!---------'.$id; $this->id = $id; } /** * Get the channels the event should broadcast on. * * @return IlluminateBroadcastingChannel|array */ public function broadcastOn() { return new PrivateChannel('channel-name'); }}
2、app/Listeners/EmailVerified.php(監(jiān)聽(tīng)器)
編輯監(jiān)聽(tīng)器
<?php namespace AppListeners; use AppEventsTest;use IlluminateContractsQueueShouldQueue; use IlluminateQueueInteractsWithQueue; class EventListener{ /** * Create the event listener. * * @return void */ public function __construct() { // } public function handle(Test $event) { echo '監(jiān)聽(tīng)成功!監(jiān)聽(tīng)值:'.$event->id; }}
在控制器中觸發(fā)事件
public function test1(){ event(new Test('11111111')); return '測(cè)試事件系統(tǒng)';}
常用命令
php artisan event:generate php artisan make:event UserRegisteredEvent php artisan make:listener SendMailListener --event="UserRegisteredEvent"
相關(guān)推薦:最新的五個(gè)Laravel視頻教程
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END