先飚幾句英文,說(shuō)說(shuō) Laravel Echo 的作用:
One of my favorite projects in the Laravel ecosystem is Echo. Echo enables real-time web applications through the use of WebSockets and hooks directly into Laravel's event broadcasting features. This means developers can use a familiar PHP API to send real-time data. A very common use-case for this type of functionality would be a notification or chat system.
翻譯「略」
摘自:https://www.imarc.com/blog/realtime-notifications-with-laravel-echo-server-docker-and-traefik
官方文檔推薦使用 Pusher 或者 laravel-echo-server (是一個(gè)使用 NodeJS + Socket.IO 實(shí)現(xiàn)的 WebSocket 服務(wù)端)。
推薦:laravel教程
在國(guó)內(nèi),個(gè)人還是不推薦使用 Pusher,訪問(wèn)速度有所影響,而且其還是一個(gè)商業(yè)產(chǎn)品。
今天利用最簡(jiǎn)便的「16」步,走一遍代碼集成 laradock 和 laravel-echo-server 來(lái)使用 Laravel Echo。
搭建基礎(chǔ)環(huán)境
// 1. new project laravel new echolearning // 2. 使用 laradock git clone https://github.com/Laradock/laradock.git // 3. 創(chuàng)建 .env cp env-example .env // 4. 創(chuàng)建 container docker-compose up -d php-worker laravel-echo-server nginx redis
// 5. 進(jìn)入 workspace 容器 docker-compose exec --user=laradock workspace bash // 6. 安裝插件 // 6.1 推薦使用 laravel-china 維護(hù)的 composer 國(guó)內(nèi)鏡像 composer config -g repo.packagist composer https://packagist.laravel-china.org // 6.2 并行下載插件 composer global require "hirak/prestissimo" // 6.3 配置 yarn 國(guó)內(nèi)鏡像 yarn config set registry 'https://registry.npm.taobao.org' // 注:以上可以在 laradock 中配置 // 6.4 執(zhí)行安裝 composer install yarn install // 7. 創(chuàng)建 .env 和 key cp .env.example .env php artisan key:generate
好了,我們開始在瀏覽器輸入:http://localhost,網(wǎng)站跑起來(lái)了
使用 Laravel Echo Server
因?yàn)?laradock 集成了「Laravel Echo Server」,所以我們很方便的使用到 Laravel Echo。
// 8. 配置廣播驅(qū)動(dòng)和 redis 服務(wù)器 BROADCAST_DRIVER=redis REDIS_HOST=redis // 9. 安裝 predis composer require predis/predis
準(zhǔn)備好后端配置后,我們開始安裝前端插件,畢竟 Laravel Echo 是前端工具。
// 10. 安裝 socket.io-client laravel-echo yarn add socket.io-client laravel-echo
在 resources/assets/js/bootstrap.js 實(shí)例化 Echo:
// 11. 實(shí)例化 Echo import Echo from 'laravel-echo' window.io = require('socket.io-client') window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' }); // Laravel 官方推薦使用 pusher // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: process.env.MIX_PUSHER_APP_KEY, // cluster: process.env.MIX_PUSHER_APP_CLUSTER, // encrypted: true // });
接下來(lái)我們就可以使用 Echo 實(shí)例,監(jiān)聽后端發(fā)過(guò)來(lái)的廣播或者通知了。
首先我們利用已經(jīng)給的 ExampleComponent 改造下,創(chuàng)建 Echo 監(jiān)聽,等待數(shù)據(jù)的到來(lái),然后再顯示在頁(yè)面上。代碼簡(jiǎn)單:
<template> <div> <div class="row justify-content-center"> <div> <div class="card card-default"> <div>Example Component</div> <div> <ul> <li v-for="name in names" :key="name">{{ name }}</li> </ul> </div> </div> </div> </div> </div> </template> <script> export default { data () { return { names: [] } }, mounted() { let that = this // 12. 創(chuàng)建 Echo 監(jiān)聽 Echo.channel('rss') .listen('RssCreatedEvent', (e) => { that.names.push(e.name) }); } } </script>
我們?cè)诤蠖颂砑右粋€(gè) rss 被創(chuàng)建的事件 RssCreatedEvent,并繼承 ShouldBroadcast。
// 13. 創(chuàng)建 RssCreatedEvent 事件 php artisan make:event RssCreatedEvent
我們使用假數(shù)據(jù),讓它返回當(dāng)前的時(shí)間,方便查看效果:
<?php namespace AppEvents; use CarbonCarbon; use IlluminateBroadcastingChannel; use IlluminateQueueSerializesModels; use IlluminateBroadcastingPrivateChannel; use IlluminateBroadcastingPresenceChannel; use IlluminateFoundationEventsDispatchable; use IlluminateBroadcastingInteractsWithSockets; use IlluminateContractsBroadcastingShouldBroadcast; class RssCreatedEvent implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct() { // } /** * Get the channels the event should broadcast on. * * @return IlluminateBroadcastingChannel|array */ public function broadcastOn() { // 14. 創(chuàng)建頻道 return new Channel('rss'); } /** * 指定廣播數(shù)據(jù)。 * * @return array */ public function broadcastWith() { // 返回當(dāng)前時(shí)間 return ['name' => Carbon::now()->toDateTimeString()]; } }
然后我們就可以做一個(gè)定時(shí)任務(wù)了,讓它每隔一分鐘,廣播一次:
protected function schedule(Schedule $schedule) { // 15. 每隔一分鐘執(zhí)行一次 $schedule->call(function () { event(new RssCreatedEvent()); })->everyMinute(); }
最后讓首頁(yè)加載 vue 組件,刷新測(cè)試:
<!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="csrf-token" content="{{ csrf_token() }}"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> </head> <body> <div id="app"> <example-component></example-component> </div> <script src="{{ asset('js/app.js') }}"></script> </body> </html>
注:需要在 header 引入
<meta name="csrf-token" content="{{ csrf_token() }}">
編譯前端:
// 16. 運(yùn)行 watch yarn run watch-poll
刷新網(wǎng)頁(yè),查看運(yùn)行效果:
如我們所愿,每隔一分鐘,廣播一次,前端 laravel-echo 監(jiān)聽并捕獲該廣播,然后讀取數(shù)據(jù),展示出來(lái)。
總結(jié)
到目前為止,我們用到的技術(shù)都有:
1.laradock 的使用
2.laravel echo server 的使用
3.廣播事件
4.event() 輔助函數(shù)
5.$schedule 定時(shí)任務(wù)
6.Laravel Echo 的使用
我們基本可以使用 Laravel Echo 了,至于更深入的使用,推薦查看官網(wǎng)文檔。
最后再一次強(qiáng)烈推薦大家用 laradock 來(lái)部署 Docker 開發(fā)環(huán)境,因?yàn)槟阆胍玫降墓ぞ吆铜h(huán)境,相信 laradock 都為你準(zhǔn)備好了。