search
HomeBackend DevelopmentPHP TutorialIntroduction 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 &#39;wechat.login&#39;;
 }
}

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 [&#39;user&#39; => $this->user->id];
 }

Node.js and Socket.io

对于发布出去的信息,我们需要一个服务来对接,让其能对 redis 的发布能够进行订阅,并且能把信息以 WebSocket 协议转发出去,这里我们可以借用 Node.js 和 socket.io 来非常方便的构建这个服务:


// server.js
var app = require(&#39;http&#39;).createServer(handler);
var io = require(&#39;socket.io&#39;)(app);

var Redis = require(&#39;ioredis&#39;);
var redis = new Redis();

app.listen(6001, function () {
 console.log(&#39;Server is running!&#39;) ;
});

function handler(req, res) {
 res.writeHead(200);
 res.end(&#39;&#39;);
}

io.on(&#39;connection&#39;, function (socket) {
 socket.on(&#39;message&#39;, function (message) {
 console.log(message)
 })
 socket.on(&#39;disconnect&#39;, function () {
 console.log(&#39;user disconnect&#39;)
 })
});


redis.psubscribe(&#39;*&#39;, function (err, count) {
});

redis.on(&#39;pmessage&#39;, function (subscrbed, channel, message) {
 message = JSON.parse(message);
 io.emit(channel + &#39;:&#39; + message.event, message.data);
});

这里我们使用 Node.js 引入 socket.io 服务端并监听 6001 端口,借用 redis 的 psubscribe 指令使用通配符来快速的批量订阅,接着在消息触发时将消息通过 WebSocket 转发出去。

Socket.io 客户端

在 web 前端,我们需要引入 Socket.io 客户端开启与服务端 6001 端口的通讯,并订阅频道事件:


// client.js
let io = require(&#39;socket.io-client&#39;)

var socket = io(&#39;:6001&#39;)
  socket.on($channel + &#39;:wechat.login&#39;, (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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
laravel单点登录方法详解laravel单点登录方法详解Jun 15, 2022 am 11:45 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

一起来聊聊Laravel的生命周期一起来聊聊Laravel的生命周期Apr 25, 2022 pm 12:04 PM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

laravel中guard是什么laravel中guard是什么Jun 02, 2022 pm 05:54 PM

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法怎么用laravel中asset()方法怎么用Jun 02, 2022 pm 04:55 PM

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

实例详解laravel使用中间件记录用户请求日志实例详解laravel使用中间件记录用户请求日志Apr 26, 2022 am 11:53 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

laravel中间件基础详解laravel中间件基础详解May 18, 2022 am 11:46 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

laravel路由文件在哪个目录里laravel路由文件在哪个目录里Apr 28, 2022 pm 01:07 PM

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。

laravel的fill方法怎么用laravel的fill方法怎么用Jun 06, 2022 pm 03:33 PM

在laravel中,fill方法是一个给Eloquent实例赋值属性的方法,该方法可以理解为用于过滤前端传输过来的与模型中对应的多余字段;当调用该方法时,会先去检测当前Model的状态,根据fillable数组的设置,Model会处于不同的状态。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment