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'); } }