Rumah  >  Artikel  >  rangka kerja php  >  Laravel利用pusher推送消息的方法详解

Laravel利用pusher推送消息的方法详解

藏色散人
藏色散人ke hadapan
2020-01-26 14:32:533621semak imbas

Laravel利用pusher推送消息的方法详解

一.注册pusher

1.注册

https://pusher.com/

2.获取key,密匙,app_id等

 

二.配置pusher

1.安装pusher

composer require pusher/pusher-php-server

2.配置config/broadcasting.php

'default' => env('BROADCAST_DRIVER', 'pusher'),
....
'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_KEY'),
            'secret' => env('PUSHER_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => 'ap1',
                'encrypted' => true
            ],
        ],
.....

三.建立事件

1.代码如下:

<?php
 
namespace App\Events;
 
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
 
class PusherEvent extends Event implements ShouldBroadcast
{
    use SerializesModels;
 
    public $info;
 
    /**
     * PusherEvent constructor.
     */
    public function __construct($info)
    {
        $this->info = $info;
    }
 
    /**
     * 指定广播频道(对应前端的频道)
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [&#39;my-channel&#39;];
    }
 
    /**
     * 指定广播事件(对应前端的事件)
     * @return string
     */
    public function broadcastAs()
    {
        return &#39;my-event&#39;;
    }
 
    /**
     * 获取广播数据,默认是广播的public属性的数据
     */
    public function broadcastWith()
    {
        return [&#39;info&#39; => $this->info];
    }
}

2.广播事件,并不需要监听器;广播事件需要继承接口ShouldBroadcast

 

四.广播

1.触发事件

event(new \App\Events\PusherEvent(&#39;测试&#39;));

2.前端代码

<!DOCTYPE html>
<head>
  <title>Pusher Test</title>
  <script src="https://js.pusher.com/4.0/pusher.min.js"></script>
  <script>
 
    // Enable pusher logging - don&#39;t include this in production
    Pusher.logToConsole = true;
 
    var pusher = new Pusher(&#39;XXX&#39;, {
      cluster: &#39;ap1&#39;,
      encrypted: true
    });
 
    var channel = pusher.subscribe(&#39;my-channel&#39;);
    channel.bind(&#39;my-event&#39;, function(data) {
      alert(data.info);
    });
  </script>
</head>

ps:

1.pusher使用curl向https://pusher.com提交数据,所以你需要配置证书;否则提交会失败

2.如果不配置证书,则需要设置curl的CURLOPT_SSL_VERIFYPEERCURLOPT_SSL_VERIFYHOST

vender/pusher/pusher-php-server/lib/Pusher.php中的trigger的

curl_setopt($ch, CURLOPT_POSTFIELDS, $post_value);

下面增加:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

更多laravel框架相关技术文章,请访问laravel教程栏目!

Atas ialah kandungan terperinci Laravel利用pusher推送消息的方法详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:cnblogs.com. Jika ada pelanggaran, sila hubungi admin@php.cn Padam