


Let's talk about the broadcast mechanism of laravel7.0, there is always what you want!
laravel7.0 broadcast mechanism (Redis socket.io)
Broadcast service provider
Before broadcasting any event, you first need to registerApp\ Providers\BroadcastServiceProvider
. In the newly installed Laravel application, you only need to uncomment the corresponding service provider in the providers
array in the config/app.php
configuration file. This provider allows you to register broadcast authorization routes and callbacks
Related column tutorial recommendations: "laravel tutorial"
Setting up Redis connection
Need to modify the broadcast driver in the .env
file to redis
:
BROADCAST_DRIVER=redis
Create Event
php artisan make:event OrderShipped
After executing the appeal command, an Events directory will appear in the app directory, and the broadcast event class OrderShipped.php
will be generated in this directory. We need to make the following modifications to the automatically generated OrderShipped class
Add the implementation of ShouldBroadcast
Modify the broadcastOn method and use the public broadcast channel orderStatus
Customize the broadcast message name (Not required) [By default, Laravel will use the class name of the event to broadcast the event, but you can pass it in the event Define the broadcastAs method in to customize the broadcast name:】
Modify the constructor
The complete modification is as follows and can be directly replaced
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class OrderShipped implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; //可添加任意成员变量 public $id; //事件构造函数 public function __construct($id) { $this->id = $id; } //自定义广播的消息名 public function broadcastAs() { return 'anyName'; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('orderStatus'); } }
Set api routing
Route::get('/ship', function (Request $request) { $id = $request->input('id'); broadcast(new OrderShipped($id)); // 触发事件 return 'Order Shipped!'; });
Install front-end scaffolding
composer require laravel/uiphp artisan ui vue --auth
Redis
Because we use Redis broadcast , you need to install the Predis library:
composer require predis/predis
Redis broadcast uses the pub/sub function of Redis for broadcast; however, you need to combine it with the one that can accept Redis The Websocket server of the message is paired to broadcast the message to the Websocket channel
When Redis broadcasts an event, the event will be published to the specified channel, and the data passed is in a JSON format string, which contains the event name, load data data, and the user who generated the event socket ID
Install laravel-echo-server and subscribe to Redis Sub
If you use pusher, then directly Just use laravel. If you use Redis socket.io, you need to use the open source project laravel-echo-server. So now we are going to use laravel-echo-server
Global installation
npm install -g laravel-echo-server
Initialize laravel-echo-server
laravel-echo-server init
// 是否在开发模式下运行此服务器(y/n) 输入y
? Do you want to run this server in development mode? (y/N)// 设置服务器的端口 默认 6001 输入 6001就可以了 或者你想要的
? Which port would you like to serve from? (6001)// 想用的数据库 选择 redis
? Which database would you like to use to store presence channel members? (Use arrow keys)❯ redis
sqlite
// 这里输入 你的laravel 项目的访问域名
? Enter the host of your Laravel authentication server. (http://localhost)// 选择 网络协议 http
? Will you be serving on http or https? (Use arrow keys)❯ http
https
// 您想为HTTP API生成客户端ID/密钥吗 N
? Do you want to generate a client ID/Key for HTTP API? (y/N)// 要设置对API的跨域访问吗?(y/n)N
Configuration file saved. Run laravel-echo-server start to run server.
//您希望将此配置另存为什么? (laravel-echo-server.json)回车就行
? What do you want this config to be saved as? (laravel-echo-server.json)
Start laravel-echo-server
laravel-echo-server start
- After successful startup, it will Output the following log
L A R A V E L E C H O S E R V E R version 1.6.0 ⚠ Starting server in DEV mode... ✔ Running at localhost on port 6001 ✔ Channels are ready. ✔ Listening for http events... ✔ Listening for redis events... Server ready!
Test broadcast
Execute on the browserhttp://yourhost/api/ship?id=16
Channel: laravel_database_orderStatus
Event: anyName
- laravel-echo-server Connection successful!
Install the pre-dependency of laravel-echo
Since the front-end uses laravel-echo
to listen to the broadcast, the underlying implementation we chose is socket.io
. So first we need to add laravel-echo
and socket.io
dependencies
npm i --save socket.io-client npm i --save laravel-echo
Edit resource/js/bootstrap.js and add the following code
import Echo from "laravel-echo";
window.io = require("socket.io-client");
window.Echo = new Echo({
broadcaster: "socket.io",
host: window.location.hostname + ":6001"
});
测试页面
在 resources/views/
下建立页面 test.blade.php 内容为
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content=""> <title>News Room</title> <link href="" rel="stylesheet"> </head> <body> <div class="content"> News Room </div> <script src=""></script> <script> Echo.channel("laravel_database_orderStatus") // 广播频道名称 .listen(".anyName", e => { // 消息名称 console.log(e); // 收到消息进行的操作,参数 e 为所携带的数据 }); </script> </body> </html>
js 代码的意思是收听 news 通道内的 News 事件对象,将接收到的事件在控制台打印出来。
基本构建
npm install && npm run watch
相关推荐:最新的五个Laravel视频教程
The above is the detailed content of Let's talk about the broadcast mechanism of laravel7.0, there is always what you want!. For more information, please follow other related articles on the PHP Chinese website!

Laravelcanbeeffectivelyusedinreal-worldapplicationsforbuildingscalablewebsolutions.1)ItsimplifiesCRUDoperationsinRESTfulAPIsusingEloquentORM.2)Laravel'secosystem,includingtoolslikeNova,enhancesdevelopment.3)Itaddressesperformancewithcachingsystems,en

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.


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

Atom editor mac version download
The most popular open source editor

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.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

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