介紹
觸發和監聽事件的一個工具。
當主業務中需要做一些其他附屬操作時,附屬操作的代碼在監聽器中實現。
event(事件) listener(監聽)
比如,在controller中寫event(xxx),表示這裏發生了一件這個事兒。
監聽器Listener就監聽到了這個事兒,然後就根據監聽器中寫好的代碼去處理該事件。
這樣做的好處就是解耦了,業務代碼中只需要關心主線邏輯,附加的一些需要處理的東西在事件中處理。
這樣多人開發的話,就很簡單,開發事件的人不須要管哪裏使用了。
使用例子
假設有這麼一個場景,當用戶訪問test方法時,通過監聽事件去做一些額外的事情。
-
註冊事件和事件監聽器。
在EventServiceProvider中添加一個listen,這裏事件名稱爲TestEvent,監聽器名稱爲TestEventListener。
app/Providers/EventServiceProvider.php:<?php namespace App\Providers; use Illuminate\Support\Facades\Event; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'App\Events\TestEvent' => [ 'App\Listeners\TestEventListener', ], ]; /** * Register any events for your application. * * @return void */ public function boot() { parent::boot(); // } }
-
生成事件文件和事件監聽器文件
在cli執行php artisan event:generate命令,生成:
app/Events/TestEvent.php
app/Listeners/TestEventListener.php -
在事件文件TestEvent.php中設置觸發事件時傳入的參數。
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class TestEvent { use InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct($test) // 這裏接收一個參數,在業務代碼中觸發這個事件時傳遞進來。 { $this->test = $test; } /** * Get the channels the event should broadcast on. * * @return Channel|array */ public function broadcastOn() { return new PrivateChannel('channel-name'); } }
-
在事件監聽器文件TestEventListener.php中寫對該事件的處理代碼。
<?php namespace App\Listeners; use App\Events\TestEvent; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Log; class TestEventListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param TestEvent $event * @return void */ public function handle(TestEvent $event) { $test = $event->test; // 將TestEvent類中設置的參數取出 // 寫業務邏輯,比如發短信、通知第三方、等等.. log::info($test); // 這裏用寫log來證明事件的觸發情況 } }
-
在業務邏輯中使用上面的事件觸發器。
<?php namespace App\Http\Controllers; ... use App\Events\TestEvent; class TestController extends Controller { ... public function test(Request $request) { ... event(new TestEvent('hello')); // 觸發test事件 ... } ... }
當程序運行到TestController的test方法時,通過event函數這裏,就會觸發TestEvent這個事件,然後該事件的監聽器去處理該事件。
根據事件監聽器的處理,最終log文件中就會多出來一行hello的log。
參考鏈接
https://blog.csdn.net/li8483468/article/details/87979295
https://learnku.com/articles/20712