2019年08月04日20:16:21 XXMphp
接於上篇博客: 打造你的Laravel即時應用(一)-項目初始化構建laravel
在上一篇博客中,介紹了項目的基本構建,如今進入實戰操做.npm
Laravel的廣播推送經過Event來實現,下面經過artisan命令來建立一個事件類bootstrap
php artisan make:event TestEvent
爲了配合咱們的廣播系統使用須要實現==IlluminateContractsBroadcastingShouldBroadcast==接口,就像這樣segmentfault
class TestEvent implements ShouldBroadcast
更改==broadcastOn==返回的Channel對象socket
public function broadcastOn() { return new Channel('notice'); }
須要安裝laravel-echo及 socket. io client這兩個包測試
npm install --save socket.io-client npm install --save laravel-echo
安裝完成後,打開==resources/assets/js/bootstrap.js==文件,添加包含基本Echo對象構建的代碼ui
import Echo from 'laravel-echo' window.io = require('socket.io-client'); window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });
構建完成後,在咱們的js代碼中開始監聽頻道事件.this
PS:更改後記得運行==npm run prod || npm run dev==socket.io
window.Echo.channel('test-event') .listen('ExampleEvent', (e) => { console.log(e); });
咱們經過添加一條路由來測試
Route::get('/notice',function(){ $event = event(new \App\Events\TestEvent('測試通知')); });
頁面監聽效果以下:
以上就完成了基本的消息推送和監聽,固然還有更多的技巧沒有展現到位,有興趣的同窗能夠查詢文檔: https://laravel.com/docs/5.6/... 來得到更多的知識和技巧.
==TestEvent.php== 完整代碼以下:
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class TestEvent implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; public $message; /** * Create a new event instance. * * @return void */ public function __construct($message) { $this->message = $message; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('notice'); } }