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.
Translate “omitted”
From: www.imarc.com/blog/realti…
The official documentation recommends using Pusher or Laravel-echo-server (a WebSocket server implemented using NodeJS + socket. IO).
In China, it is still not recommended for individuals to use Pusher because access speed is affected and it is a commercial product.
Today, using the easiest “16” steps, walk through the code to integrate Laradock and Laravel-Echo-server to use Laravel Echo.
Setting up the infrastructure
// 1. new project laravel new echolearning // 2. Using laradock gitclonehttps://github.com/Laradock/laradock.git // 3. Create. Env cp env.example. Create container Docker-compose Up-d php-worker laravel-echo-server nginx redis
Copy the code
// 5. 进入 workspace 容器
docker-compose exec--user=laradock workspace bash // 6. 6.1 You are advised to use the local mirrored composer maintained by Laravel-China, config -g repo.packagist Composer HTTP: / / https://packagist.laravel-china.org / 6.2 / parallel downloads plug-in composer global the require"hirak/prestissimo"// 6.3 Configuring yarn Domestic mirroring yarn configset registry 'https://registry.npm.taobao.org'// Note: The above can be configured in Laradock. // 6.4 Executing installation Composer install yarn install. Env PHP artisan key:generateCopy the code
Ok, we started typing http://localhost into the browser, and the site took off
Use the Laravel Echo Server
Because Laradock integrates “Laravel Echo Server”, it is very easy to use Laravel Echo.
BROADCAST_DRIVER=redis REDIS_HOST=redis // Install predis Composer require predis/predisCopy the code
With the back-end configuration ready, we started installing the front-end plug-in, since Laravel Echo is a front-end tool after all.
IO -client laravel-echo yarn add socket. IO -client laravel-echo // 10Copy the code
In the resources/assets/js/bootstrap. Js instantiation Echo:
11. Instantiate 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 officially recommends using 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
// });
Copy the code
We can then use the Echo instance to listen for broadcasts or notifications from the back end.
Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Simple code:
<template> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card card-default"> <div class="card-header">Example Component</div> <div class="card-body"> <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. Echo Echo. Channel (' RSS ').listen('RssCreatedEvent', (e) => {that.names.push(e.name)}); } } </script>Copy the code
We add an RssCreatedEvent event created by RSS to the back end and inherit ShouldBroadcast.
PHP artisan make:event RssCreatedEventCopy the code
We use fake data and make it return the current time so that we can see the effect:
namespace App\Events;
use Carbon\Carbon;
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 RssCreatedEvent implements ShouldBroadcast
{
use Dispatchable.InteractsWithSockets.SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(a)
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn(a)
{
// create a channel
return new Channel('rss');
}
/** * Specifies broadcast data. * *@return array
*/
public function broadcastWith(a)
{
// Return the current time
return ['name'=> Carbon::now()->toDateTimeString()]; }}Copy the code
And then we can do a timed task and have it broadcast every minute:
protected function schedule(Schedule $schedule)
{
// 15. Execute every minute
$schedule->call(function (a) {
event(new RssCreatedEvent());
})->everyMinute();
}
Copy the code
Finally, let the home page load vUE component, refresh the test:
<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>
Copy the code
Note: Need to be introduced in header
<meta name="csrf-token" content="{{ csrf_token() }}">
Copy the code
Compile front end:
// 16. Run watch yarn run watch-pollCopy the code
Refresh the web page to view the running effect:
Every minute, as we wanted, we broadcast, and the front-end Laravel-Echo listens and captures that broadcast, and then reads the data and displays it.
conclusion
So far, the techniques we’ve used include:
- The use of laradock
- Laravel Echo Server usage
- Broadcast events
- The event() helper function
- $schedule Indicates the scheduled task
Laravel Echo
The use of
The Laravel Echo is almost ready to use, but for more in-depth use, I recommend checking out the documentation on our website.
Finally, laradock is highly recommended to deploy Docker development environment, because you want to use the tools and environment, I believe laradock is ready for you.
“Finished”