


Introduction to 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. For reference, let’s learn with the editor below.
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 configuration file of Redis 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 to log in:
<?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, It 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 send the information Broadcast it out. 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 隧道,并对事件进行订阅,根据指定事件的推送进行响应。
总结
The above is the detailed content of Introduction to Laravel's method of building instant applications. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

PHP unit testing tool analysis: PHPUnit: suitable for large projects, provides comprehensive functionality and is easy to install, but may be verbose and slow. PHPUnitWrapper: suitable for small projects, easy to use, optimized for Lumen/Laravel, but has limited functionality, does not provide code coverage analysis, and has limited community support.

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

PHP Unit and Integration Testing Guide Unit Testing: Focus on a single unit of code or function and use PHPUnit to create test case classes for verification. Integration testing: Pay attention to how multiple code units work together, and use PHPUnit's setUp() and tearDown() methods to set up and clean up the test environment. Practical case: Use PHPUnit to perform unit and integration testing in Laravel applications, including creating databases, starting servers, and writing test code.
