Pusherとはwebsocketを提供するAPIで、アカウント登録することで無料である程度使えます。チャットやリアルタイム通知など実装するときに使えます。
LaravelでPusherを利用したときの手順を残しておきます。
- Pusherの公式サイト(https://dashboard.pusher.com/accounts/sign_in)でアカウントを作成。
- ログインし、”app”を作成。
※”app name”はアプリケーション名、”cluster”は”ap3″、”front-end”は”jquery”、”back-end”は”laravel”を選択 - ターミナルで以下コマンドを実行し、プロジェクトにpusherをインストール。
1composer require pusher/pusher-php-server - 以下コマンドでEventクラスを生成。
1php artisan make:event "イベント名" - 作成したイベントクラスを以下のように書き換える。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546<?phpnamespace App\Events;use Illuminate\Broadcasting\Channel;use Illuminate\Queue\SerializesModels;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;use Illuminate\Console\Scheduling\Event;class PusherEvent extends Event implements ShouldBroadcast{use 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 Channel|array*/public function broadcastOn(){return ['channel_name'];}/**** @return string*/public function broadcastAs(){return 'event_name';}} - “/config/app.php”の”providers”の以下のコメントアウトを外す。
1// App\Providers\BroadcastServiceProvider::class, - Pusherの管理画面で確認した”app_id”, “key”, “secret”, “cluster”をそれぞれ.envファイルに設定。また、.envの”BROADCAST_DRIVER”を”pusher”に設定。
- この状態で、controllerなどでイベントをnewすれば、Pusherに通知が行くはず。
- Pusherからの通知はJavaScriptで受け取る。記述例は以下の通り。
12345678910111213// Pusherキーvar pusher = new Pusher('{{ env('PUSHER_APP_KEY') }}', {cluster : 'ap3',encrypted: true});// LaravelのEventクラスで設定したチャンネル名var pusherChannel = pusher.subscribe('cnannel_name');// イベントを受信したらコールバック関数を実行pusherChannel.bind('pusher_event', function(data) {//処理});
以上です。
コメント