The usage process of Echo in Laravel framework
Today’s article will share with you about the use of echo in the laravel framework. The content of the article is step by step. It took 16 steps to complete a process. The process is very clear. I hope it can help friends in need. Bar. Without further ado, let’s get straight to the content.
Pusher
or laravel-echo-server
(which is an implementation using NodeJS
Socket.IO
WebSocket
server). In China, individuals still do not recommend using Pusher
, as the access speed will be affected, and it is still a commercial product.
Today, take advantage of the simplest "16" steps and go through the code integration laradock
and laravel-echo-server
to use Laravel Echo
.
Build the basic environment
// 1. new project laravel new echolearning // 2. 使用 laradock git clone https://github.com/Laradock/laradock.git // 3. 创建 .env cp env-example .env // 4. 创建 container docker-compose up -d php-worker laravel-echo-server nginx redis
##
// 5. 进入 workspace 容器 docker-compose exec --user=laradock workspace bash // 6. 安装插件 // 6.1 推荐使用 laravel-china 维护的 composer 国内镜像 composer config -g repo.packagist composer https://packagist.laravel-china.org // 6.2 并行下载插件 composer global require "hirak/prestissimo" // 6.3 配置 yarn 国内镜像 yarn config set registry 'https://registry.npm.taobao.org' // 注:以上可以在 laradock 中配置 // 6.4 执行安装 composer install yarn install // 7. 创建 .env 和 key cp .env.example .env php artisan key:generate
Using Laravel Echo Server
Because laradock integrates " Laravel Echo Server", so we can useLaravel Echo very conveniently.
// 8. 配置广播驱动和 redis 服务器 BROADCAST_DRIVER=redis REDIS_HOST=redis // 9. 安装 predis composer require predis/predis
Laravel Echo is a front-end tool.
// 10. 安装 socket.io-client laravel-echo yarn add socket.io-client laravel-echo
Echo in
resources/assets/js/bootstrap.js:
// 11. 实例化 Echo import Echo from 'laravel-echo' window.io = require('socket.io-client') window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' }); // Laravel 官方推荐使用 pusher // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: process.env.MIX_PUSHER_APP_KEY, // cluster: process.env.MIX_PUSHER_APP_CLUSTER, // encrypted: true // });
Echo Example, listen for broadcasts or notifications sent from the backend.
ExampleComponent we have given to transform it, create an
Echo listener, wait for the arrival of data, and then display it on the page. The code is simple:
<template> <p> </p> <p> </p> <p> </p> <p> </p> <p>Example Component</p> <p> </p> <ul> <li>{{ name }}</li> </ul> </template> <script> export default { data () { return { names: [] } }, mounted() { let that = this // 12. 创建 Echo 监听 Echo.channel('rss') .listen('RssCreatedEvent', (e) => { that.names.push(e.name) }); } } </script>
rss created event
RssCreatedEvent in the backend and inherit
ShouldBroadcast.
// 13. 创建 RssCreatedEvent 事件 php artisan make:event RssCreatedEvent
<?php namespace App\Events; use Carbon\Carbon; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class RssCreatedEvent implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct() { // } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { // 14. 创建频道 return new Channel('rss'); } /** * 指定广播数据。 * * @return array */ public function broadcastWith() { // 返回当前时间 return ['name' => Carbon::now()->toDateTimeString()]; } }
protected function schedule(Schedule $schedule) { // 15. 每隔一分钟执行一次 $schedule->call(function () { event(new RssCreatedEvent()); })->everyMinute(); }
vue component and refresh the test:
nbsp;html> getLocale() }}"> <meta> <meta> <meta> <meta> <title>Laravel</title> <p> <example-component></example-component> </p> <script></script>
<meta>
needs to be introduced in
header to compile Front-end:
// 16. 运行 watch yarn run watch-poll
laravel-echo listens and captures the broadcast, then reads the data and displays it.
Summary
So far, the technologies we have used are: 1. The use of laradock2. Use of laravel echo server3. Broadcast event4.event() auxiliary function5.$schedule scheduled task6.Laravel Echo The useWe can basically useLaravel Echo. As for more in-depth use, it is recommended to check the official website documentation.
laradock to deploy the Docker development environment, because I believe
laradock has prepared all the tools and environments you want to use for you. .
laravel framework introductory tutorial.
Recommended related articles:Code analysis of the Autoloader module in the Laravel framework
In-depth analysis of the appearance mode in the Laravel framework
Related course recommendations:The latest five Laravel video tutorial recommendations in 2017
The above is the detailed content of The usage process of Echo in Laravel framework. 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



LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

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.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
