Home>Article>PHP Framework> An article explaining in detail how to quickly create a simple event flow in Laravel

An article explaining in detail how to quickly create a simple event flow in Laravel

Michael Jordan
Michael Jordan forward
2023-01-04 16:07:03 1237browse

This article brings you relevant knowledge about Laravel event flow. It mainly introduces what event flow is and how to create a simple event flow in Laravel. Interested friends should take a look. I hope everyone has to help.

Introduction

Event streaming provides you with a way to send events to the client without reloading the page. This is useful for updating the user interface when live changes are made to the database.

Unlike traditional long polling using AJAX requests, in which multiple requests are sent to the server and a new connection is established each time, the event stream is sent to the client in real time in a single request .

An article explaining in detail how to quickly create a simple event flow in Laravel

In this article, I will show you how to create a simple event stream in Laravel.

Prerequisites

Before you begin, you need to have Laravel installed on your machine.

I will be using the DigitalOcean Ubuntu Droplet in this demo. If you'd like, you can use my affiliate code to getfree $100 DigitalOcean creditsto launch your own server!

If you haven't already, you can follow the steps in this tutorial:

Or you can install it using this awesome script:

Create a Controller

Let's start by creating a controller that handles the event stream.

Use the following command:

php artisan make:controller EventStreamController

This will create a new controller in the App\Http\Controllers directory.

Adding Event Streaming Methods

Once we have created our controller, we need to add thestreammethod to it. This method will be used to send a stream of events.

Open theEventStreamController.phpfile and add the following code:

stream(function () { while (true) { echo "event: ping\n"; $curDate = date(DATE_ISO8601); echo 'data: {"time": "' . $curDate . '"}'; echo "\n\n"; $trades = Trade::latest()->get(); echo 'data: {"total_trades":' . $trades->count() . '}' . "\n\n"; $latestTrades = Trade::with('user', 'stock')->latest()->first(); if ($latestTrades) { echo 'data: {"latest_trade_user":"' . $latestTrades->user->name . '", "latest_trade_stock":"' . $latestTrades->stock->symbol . '", "latest_trade_volume":"' . $latestTrades->volume . '", "latest_trade_price":"' . $latestTrades->stock->price . '", "latest_trade_type":"' . $latestTrades->type . '"}' . "\n\n"; } ob_flush(); flush(); // 如果客户端中止连接,则中断循环(关闭页面) if (connection_aborted()) {break;} usleep(50000); // 50ms } }, 200, [ 'Cache-Control' => 'no-cache', 'Content-Type' => 'text/event-stream', ]); }}

The main things to note here are:

  • We useresponse()->stream()method to create an event stream.
  • Then we have an infinite loop that sends a stream of events every 50ms.
  • If the client aborts the connection, we useob_flush()andflush()to send the event stream.
  • We usesleep()to wait 50ms before sending the next event.
  • We useconnection_aborted()to break the loop if the client aborts the connection.
  • We use theCarbon\Carbonclass to get the current date.
  • We use theApp\Models\Trademodel to get the latest transactions. This is for demonstration only, you can use any model you want.
  • Set theContent-Typeheader totext/event-streamto tell the browser that the response is an event stream.

Enable output buffering

In order for the above code to work properly, we need to enable output buffering in your PHP.ini file. This is done by adding the following line to thephp.inifile:

output_buffering = On

It may be necessary to reload the PHP-FPM service after making this change. Or if you are using Apache, you can restart Apache.

Add route

When requesting the/streamroute, we want to call the ``stream` method.

The route will be added to theroutes/web.phpfile as follows:

use App\Http\Controllers\StreamsController;Route::get('/stream', [StreamsController::class, 'stream']);

Using the event flow from the frontend

You can use Front-end frameworks such asVue.jsare used to handle event streams. But for this demo, I'm going to use pure Javascript.

The JavaScript snippet added to the blade template looks like this:

const eventSource = new EventSource('/stream');eventSource.onmessage = function(event) { const data = JSON.parse(event.data); if (data.time) { document.getElementById('time').innerHTML = data.time; } const newElement = document.createElement("li"); const eventList = document.getElementById("list"); newElement.textContent = "message: " + event.data; eventList.appendChild(newElement);}

To see this in action, you can try the following demo! [Related recommendations:laravel video tutorial]

Demo project

If you want to understand how event streaming works, you can check out the demo project I created:

Laravel EventStream: Live Stock Trading Dashboard using Laravel and Materialize

Demo project not only shows the event stream but also has a simple front-end dashboard and usesMaterializeAs a streaming database.

Laravel EventStream

SSE vs WebSockets

Event streaming is great and easy to use, but it also has some advantages and disadvantages compared to other streaming protocols likeWebSockets.

For example, SSE is one-way, which means that once the connection is established, the server can only send data to the client, and the client cannot send data back to the server.

Unlike long polling, with WebSockets you have only one connection to the server, similar to SSE (Server Sent Events). The connection is duplex, which means you can send and receive data from the server.

If you want to learn more about the differences between SSE and WebSockets, check out this great video by Martin Chaov:Links

Conclusion

Related For more information on event streaming, check out this documentation from Mozilla here:

There, You'll find a more in-depth explanation of event streaming and how it works.

For more information about Materialize, watch this video here:Link

Hope you enjoyed this tutorial!

Original address:https://devdojo.com/bobbyiliev/how-to-cr...

Translated address:https: //m.sbmmt.com/link/09d45b92ec72b3c16ac64bbe4b97f539

The above is the detailed content of An article explaining in detail how to quickly create a simple event flow in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete