라라벨 브로드캐스팅 Pusher

1 개요[ | ]

라라벨 브로드캐스팅 Pusher
  • 라라벨 브로드캐스팅 중 Pusher를 사용한 예시

2 명령어 클래스: PushHello.php[ | ]

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Events\HelloEvent;

class PushHello extends Command
{
	protected $signature = 'z:push-hello';
	protected $description = 'Push Hello message';
	public function handle()
	{
		event(new HelloEvent());
		echo "New HelloEvent!\n";
	}
}

3 이벤트 클래스: HelloEvent.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 HelloEvent implements ShouldBroadcast
{
	public function broadcastOn()
	{
		return new Channel('my-channel');
	}
	
	public function broadcastWith()
	{
		return ['message' => 'Hello World'];
	}
}

4 JavaScript[ | ]

window.Echo = new Echo({
	broadcaster: 'pusher',
	key: 'eacfbd24a6cebdf80cea',
	cluster: 'ap1'
});
window.Echo.channel('my-channel')
.listen('HelloEvent', (e) => {
	console.log("Gotcha!!");
	console.log(e);
});

5 실행과정[ | ]

root@zetawiki:/var/www/laravel# php artisan z:push-hello
New HelloEvent!
  • 큐에 다음과 같이 작업이 등록된다.
{
  "displayName": "App\\Events\\HelloEvent",
  "job": "Illuminate\\Queue\\CallQueuedHandler@call",
  "maxTries": null,
  "timeout": null,
  "data": {
    "commandName": "Illuminate\\Broadcasting\\BroadcastEvent",
    "command": "O:38:\"Illuminate\\Broadcasting\\BroadcastEvent\":4:{s:5:\"event\";O:32:\"App\\Events\\HelloEvent\":0:{}s:10:\"connection\";N;s:5:\"queue\";N;s:5:\"delay\";N;}"
  }
}
  • worker가 작업을 수행하면서 Pusher에 전달하는 파라미터 원형은 아래와 같다. (이후 암호화될 수 있음)
{
  "name": "App\\Events\\HelloEvent",
  "data": "{\"message\":\"Hello World\"}",
  "channels": [
    "my-channel"
  ]
}
  • 웹브라우저(콘솔)에서는 다음과 같이 확인된다.
Gotcha!!
{message: "Hello World"}

6 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}