4

打造你的Laravel即时应用(二)-消息推送与监听

2019年08月04日20:16:21 XXM

接于上篇博客: 打造你的Laravel即时应用(一)-项目初始化构建

在上一篇博客中,介绍了项目的基本构建,现在进入实战操作.

(一、消息推送)

1.创建事件类

Laravel的广播推送通过Event来实现,下面通过artisan命令来创建一个事件类

php artisan make:event TestEvent

为了配合我们的广播系统使用需要实现==IlluminateContractsBroadcastingShouldBroadcast==接口,就像这样

class TestEvent implements ShouldBroadcast

2.指定推送频道

更改==broadcastOn==返回的Channel对象

public function broadcastOn()
{
        return new Channel('notice');
}

3.监听消息

需要安装laravel-echo及 socket. io client这两个包

npm install --save socket.io-client 
npm install --save laravel-echo

安装完成后,打开==resources/assets/js/bootstrap.js==文件,添加包含基本Echo对象构建的代码

import Echo from 'laravel-echo'

window.io = require('socket.io-client');
window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
}); 

构建完成后,在我们的js代码中开始监听频道事件.

PS:更改后记得运行==npm run prod || npm run dev==

window.Echo.channel('test-event')
    .listen('ExampleEvent', (e) => {
        console.log(e);
    });

4.测试应用结果

我们通过添加一条路由来测试

Route::get('/notice',function(){
    $event = event(new \App\Events\TestEvent('测试通知'));
});

页面监听效果如下:
image

以上就完成了基本的消息推送和监听,当然还有更多的技巧没有展示到位,有兴趣的同学可以查询文档: 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');
    }
}

Sinming
310 声望21 粉丝

Bug总工程师