Home > Article > PHP Framework > An implementation method of Laravel instant application
Instant interactive applications
In modern web applications, many scenarios require the use of instant messaging, such as the most common payment callbacks and third-party logins. These business scenarios basically need to follow the following process:
● The client triggers related businesses and generates third-party application operations (such as payment)
● The client waits for the server response result (user Complete the operation of the third-party application)
● The third-party application notifies the server of the processing result (payment is completed)
● The server notifies the client of the processing result
● Client basis Give feedback on the result (jump to the payment success page)
In the past, in order to achieve this kind of instant messaging and allow the client to respond correctly to the processing results, the most commonly used technology was polling, because the single-step HTTP protocol Orientation, the client can only actively ask the server for the processing results over and over again. This method has obvious flaws. Not only does it occupy server-side resources, it also cannot obtain server-side processing results in real time.
Now, we can use the WebSocket protocol to handle real-time interactions. It is a two-way protocol that allows the server to actively push information to the client. In this article we will use Laravel's powerful event system to build real-time interactions. You will need the following knowledge:
● Laravel Event
● Redis
● Socket.io
● Node.js
Redis
Before we start, we need to open a redis service and configure and enable it in the Laravel application, because throughout the process, we need to use the subscription and publishing mechanism of redis to Enable instant messaging.
Redis is an open source and efficient key-value storage system. It is usually used as a data structure server to store key-value pairs, and it can support strings, hashes, lists, sets and ordered combinations. To use Redis in Laravel you need to install the predis/predis package file through Composer.
Configuration
The configuration file of Redis in the application is stored in config/database.php. In this file, you can see a file containing Redis service information. redis array:
'redis' => [ 'cluster' => false, 'default' => [ 'host' => '127.0.0.1', 'port' => 6379, 'database' => 0, ], ]
If you modify the port of the redis service, please keep the port in the configuration file consistent.
Laravel Event
Here we need to use Laravel’s powerful event broadcasting capabilities:
Broadcast Event
Many modern applications use Web Sockets to implement real-time interactive user interfaces. When some data changes on the server, a message is delivered to the client for processing via the WebSocket connection.
To help you build this type of application. Laravel makes it easy to broadcast events over a WebSocket connection. Laravel allows you to broadcast events to share the event name to your server-side and client-side JavaScript frameworks.
Configuration
All event broadcast configuration options are stored in the config/broadcasting.php configuration file. Laravel comes with several available drivers such as Pusher, Redis, and Log. We will use Redis as the broadcast driver, which requires the predis/predis class library.
Since the default broadcast driver uses pusher, we need to set BROADCAST_DRIVER=redis in the .env file.
We create a WechatLoginedEvent event class to broadcast after the user scans WeChat login:
<?php namespace App\Events; use App\Events\Event; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class WechatLoginedEvent extends Event implements ShouldBroadcast { use SerializesModels; public $token; protected $channel; /** * Create a new event instance. * * @param string $token * @param string $channel * @return void */ public function __construct($token, $channel) { $this->token = $token; $this->channel = $channel; } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return [$this->channel]; } /** * Get the name the event should be broadcast on. * * @return string */ public function broadcastAs() { return 'wechat.login'; } }
You need to note that the broadcastOn method should return an array, which represents the channel to be broadcast, and broadcastAs returns a string, which represents the event triggered by the broadcast. Laravel's default is to return the full class name of the event class. Here is App\Events\WechatLoginedEvent.
The most important thing is that you need to manually Let this class implement the ShouldBroadcast contract. Laravel has automatically added this namespace when generating events, and this contract only constrains the broadcastOn method.
After the event is completed, the next step is to trigger the event. A simple line of code is enough:
event(new WechatLoginedEvent($token, $channel));
This operation will automatically trigger the execution of the event and broadcast the information. The underlying broadcast operation relies on the subscription and publishing mechanism of redis. RedisBroadcaster will publish the publicly accessible data in the event through the given channel. If you want to have more control over the exposed data, you can add a broadcastWith method to the event, which should return an array:
/** * Get the data to broadcast. * * @return array */ public function broadcastWith() { return ['user' => $this->user->id]; }
Node.js and Socket.io
For the published information, we need a service to connect so that it can subscribe to the redis publication and forward the information using the WebSocket protocol. Here we can borrow Node.js and socket.io. It is very convenient to build this service:
// server.js var app = require('http').createServer(handler); var io = require('socket.io')(app); var Redis = require('ioredis'); var redis = new Redis(); app.listen(6001, function () { console.log('Server is running!') ; }); function handler(req, res) { res.writeHead(200); res.end(''); } io.on('connection', function (socket) { socket.on('message', function (message) { console.log(message) }) socket.on('disconnect', function () { console.log('user disconnect') }) }); redis.psubscribe('*', function (err, count) { }); redis.on('pmessage', function (subscrbed, channel, message) { message = JSON.parse(message); io.emit(channel + ':' + message.event, message.data); });
Here we use Node.js to introduce the socket.io server and listen to the 6001 port. We borrow the psubscribe command of redis to use wildcards to quickly subscribe in batches, and then when the message is triggered, Messages are forwarded via WebSocket.
Socket.io client
In the web front-end, we need to introduce the Socket.io client to open communication with the server port 6001 and subscribe to channel events:
// client.js let io = require('socket.io-client') var socket = io(':6001') socket.on($channel + ':wechat.login', (data) => { socket.close() // save user token and redirect to dashboard })
The entire closed communication loop is now over, and the development process looks like this:
● Build an event in Laravel that supports broadcast notification
● Set the channel and event name that need to be broadcast
● Set the broadcast to use the redis driver
● Provide a continuous service for subscribing to redis publications, and push the published content to the client through the WebSocket protocol
● The client opens the server WebSocket tunnel and subscribes to events, and pushes the specified events to respond.
For more Laravel related technical articles, please visit the Laravel Framework Getting Started Tutorial column to learn!
The above is the detailed content of An implementation method of Laravel instant application. For more information, please follow other related articles on the PHP Chinese website!