


Detailed explanation of Laravel's method of building instant applications
This article mainly introduces you to an implementation method of building instant applications in Laravel. Instant messaging is often encountered in our daily development. This article introduces it in detail through sample code. Friends who need it can refer to it. Let’s learn with the editor below. I hope to be helpful.
Instant interactive applications
Everyone should have experienced that instant messaging is required in many scenarios in modern Web applications. For example, the most common payment callback is related to third-party login. 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 (the user completes 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 results
The client makes feedback based on the results (jumps to the payment success page)
In In the past, in order to achieve this kind of instant communication and allow the client to respond correctly to the processing results, the most commonly used technology was polling. Because of the one-way nature of the HTTP protocol, the client could 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 begin, We need to open a redis service and configure and enable it in the Laravel application, because throughout the process, we need to use redis's subscription and publishing mechanism to achieve 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 Redis configuration file in the application is stored in config/database.php. In this file, you can see a The redis array containing the Redis service information:
'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 the 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
对于发布出去的信息,我们需要一个服务来对接,让其能对 redis 的发布能够进行订阅,并且能把信息以 WebSocket 协议转发出去,这里我们可以借用 Node.js 和 socket.io 来非常方便的构建这个服务:
// 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); });
这里我们使用 Node.js 引入 socket.io 服务端并监听 6001 端口,借用 redis 的 psubscribe 指令使用通配符来快速的批量订阅,接着在消息触发时将消息通过 WebSocket 转发出去。
Socket.io 客户端
在 web 前端,我们需要引入 Socket.io 客户端开启与服务端 6001 端口的通讯,并订阅频道事件:
// 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 })
至此整个通讯闭环结束,开发流程看起来就是这样的:
在 Laravel 中构建一个支持广播通知的事件
设置需要进行广播的频道及事件名称
将广播设置为使用 redis 驱动
提供一个持续的服务用于订阅 redis 的发布,及将发布内容通过 WebSocket 协议推送到客户端
客户端打开服务端 WebSocket 隧道,并对事件进行订阅,根据指定事件的推送进行响应。
相关推荐:
详解Laravel实现supervisor执行异步进程的方法
The above is the detailed content of Detailed explanation of Laravel's method of building instant applications. For more information, please follow other related articles on the PHP Chinese website!

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools