pusher 创建新应用_laravel之pusher应用广播事件- 黑白课堂
版本說明
composer指定版本可以查看
https://www.jianshu.com/p/ef31d9c9094b
laravel5.2
pusher版本
"pusher/pusher-php-server": "^2.2.1",
pusher laravel版本
"pusher/pusher-http-laravel": "~2.0"
安裝
忽略怎么安裝,
把創建pusher的配置文件讀取到config下,
官方文檔存在BUG,代碼應該是
php artisan vendor:publish
config/app.php
引入
'providers' => [
..
Vinkla\Pusher\PusherServiceProvider::class
]
別名那里不引入,有問題,后續有機會重寫一個
搞定配置
配置文件說明
'connections' => [
'main' => [
'auth_key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [],
'host' => null,
'port' => null,
'timeout' => null,
//這里必須增加配置,表示
'options'=>[
'encrypted'=>false,//是否HTTPS
'cluster'=>'ap1',//調用哪個api
]
],
'alternative' => [
'auth_key' => 'your-auth-key',
'secret' => 'your-secret',
'app_id' => 'your-app-id',
'options' => [],
'host' => null,
'port' => null,
'timeout' => null,
],
],
測試下是否可以使用
HTML文件,拿官方的來,訂閱
Pusher Test// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('0a8d7355056b24b3dcd9', {
cluster: 'ap1',
encrypted: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(data.message);
});
laravel文件,發布
隨便一個控制器,方法隨便你,
$pusher = App::make('pusher');//因為直接用別名,剛才說了,引入會報錯,所以用了這種方法注冊。
$data['message'] = 'hello world';
$pusher->trigger('my-channel', 'my-event', $data);
瀏覽器訪問就可以在html文件那里打開顯示hell world
事件廣播定義
創建事件定義,加入如下,這個怎么創建,請參考https://www.jianshu.com/p/68caa3df8bf5
'App\Events\PusherEvent' => [
'App\Listeners\PusherEventListener',
]
執行生成
php artisan event:generate
envent繼承ShouldBroadcast
class PusherEvent extends Event implements ShouldBroadcast
{
use SerializesModels;
public $message, $id;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($text, $id)
{
$this->message = $text;
$this->id = $id;
}
/**
* Get the channels the event should be broadcast on.
*這里是定義頻道的名字
* @return array
*/
public function broadcastOn()
{
return ['channel'];
}
//事件名字,如果這里沒有定義,則會直接以這個事件名字為事件名,例如:App\\Events\\PusherEvent;
public function broadcastAs(){
return ['my-event'];
}
}
控制器調用
$str=str_random();
$pusher = App::make('pusher');
event(new \App\Events\PusherEvent($str, '1'));//觸發事件
html文件調用
Pusher.logToConsole = true;
var pusher = new Pusher('0a8d7355056b24b3dcd9', {
cluster: 'ap1',
encrypted: true
});
var channel = pusher.subscribe('channel');
channel.bind('App\\Events\\PusherEvent', function(data) {
alert(data.message);
});
總結
以上是生活随笔為你收集整理的pusher 创建新应用_laravel之pusher应用广播事件- 黑白课堂的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微机化远动系统与计算机网络,计算机网络在
- 下一篇: UOJ#449 喂鸽子