Home > Backend Development > PHP Tutorial > An Introduction into Event Loops in PHP

An Introduction into Event Loops in PHP

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-17 10:37:09
Original
527 people have browsed it

PHP event loop: a weapon for asynchronous programming

Core points

  • PHP event loop is a programming structure used to wait for events or messages in a scheduler, especially for handling asynchronous operations.
  • Traditional PHP programming is synchronous, performing one operation at a time, and waiting for each operation to complete before continuing with the next operation. While the event loop allows asynchronous programming, where an operation can be started and then put on hold until the result is ready, other operations can be performed during this time.
  • Libraries such as ReactPHP or Amp provide the necessary interfaces and classes to create and manage PHP event loops, allowing better use of resources and shorter response times, especially in applications that need to handle a large number of concurrent connections.
  • While event loops can provide significant performance benefits, they can also increase the complexity of the application, require different programming styles, and may make the code more difficult to understand and debug. Not all tasks are suitable for asynchronous processing, and some tasks may be more difficult to implement in event loops.

PHP developers are always waiting for something. Sometimes we wait for a request for remote services. Sometimes we wait for the database to return rows from complex queries. Wouldn't that be great if we could do other operations during all the waiting periods?

If you have written some JS code, you may be familiar with callbacks and DOM events. Although we also have callbacks in PHP, they don't work exactly the same way. This is thanks to a feature called event loop.

An Introduction into Event Loops in PHP We will understand how event loops work and how to use event loops in PHP.

We will see some interesting PHP libraries. Some people believe that these libraries are not stable enough to be used in production environments. Some people think the examples provided here are "preferably implemented in a more mature language". There are many good reasons to try these methods. There are also good reasons to avoid these methods in production environments. The purpose of this article is to highlight possibilities in PHP.

Waiting place

To understand event loops, let's see how they work in the browser. Take a look at this example:

function fitToScreen(selector) {
    var element = document.querySelector(selector);

    var width = element.offsetWidth;
    var height = element.offsetHeight;

    var top = "-" + (height / 2) + "px";
    var left = "-" + (width / 2) + "px";

    var ratio = getRatio(width, height);

    setStyles(element, {
        "position": "absolute",
        "left": "50%",
        "top": "50%",
        "margin": top + " 0 0 " + left,
        "transform": "scale(" + ratio + ", " + ratio + ")"
    });
}

function getRatio(width, height) {
    return Math.min(
        document.body.offsetWidth / width,
        document.body.offsetHeight / height
    );
}

function setStyles(element, styles) {
    for (var key in styles) {
        if (element.style.hasOwnProperty(key)) {
            element.style[key] = styles[key];
        }
    }
}

fitToScreen(".welcome-screen");
Copy after login
Copy after login
Copy after login

This code does not require additional libraries. It works in any browser that supports CSS zoom conversion. The latest Chrome version is enough. Just make sure the CSS selector matches the elements in the document.

These functions receive a CSS selector and center and scale the elements to fit the screen. What happens if we throw an error in the for loop? We will see something like this...

An Introduction into Event Loops in PHP

We call this function list stack trace. This is what the inside of the stack used by the browser looks like. They will process this code in steps...

An Introduction into Event Loops in PHP

This is like how PHP uses the stack to store context. The browser goes a step further and provides WebAPI for content such as DOM events and Ajax callbacks. In its natural state, JavaScript is asynchronous as PHP. That is: while both seem to be able to perform many operations at the same time, they are both single-threaded. They can only do one thing at a time.

Using browser WebAPIs such as setTimeout and addEventListener, we can offload parallel work to different threads. When these events occur, the browser adds the callback to the callback queue. When the stack is empty next time, the browser picks up the callbacks from the callback queue and executes them.

This process of clearing the stack and then calling back queue is the event loop.

Life without event loop

In JS, we can run the following code:

function fitToScreen(selector) {
    var element = document.querySelector(selector);

    var width = element.offsetWidth;
    var height = element.offsetHeight;

    var top = "-" + (height / 2) + "px";
    var left = "-" + (width / 2) + "px";

    var ratio = getRatio(width, height);

    setStyles(element, {
        "position": "absolute",
        "left": "50%",
        "top": "50%",
        "margin": top + " 0 0 " + left,
        "transform": "scale(" + ratio + ", " + ratio + ")"
    });
}

function getRatio(width, height) {
    return Math.min(
        document.body.offsetWidth / width,
        document.body.offsetHeight / height
    );
}

function setStyles(element, styles) {
    for (var key in styles) {
        if (element.style.hasOwnProperty(key)) {
            element.style[key] = styles[key];
        }
    }
}

fitToScreen(".welcome-screen");
Copy after login
Copy after login
Copy after login

When we run this code, we see outside the timeout in the console, and then inside the timeout. The setTimeout function is part of the WebAPI provided by the browser. After 1 millisecond has elapsed, they add the callback to the callback queue.

The second console.log is done before the console.log from inside the setTimeout begins. We don't have anything like setTimeout in standard PHP, but if we have to try to simulate it:

setTimeout(function() {
    console.log("inside the timeout");
}, 1);

console.log("outside the timeout");
Copy after login

When we run it, we see inside the timeout, then outside the timeout. This is because we have to use an infinite loop in the setTimeout function to execute the callback after a delay.

It can be tempting to move while loop outside of setTimeout and include all the code in it. This may make our code feel less blocked, but at some point we will always be blocked by that loop. At some point, we will see that we can only do one thing in one thread at a time.

While there is nothing like setTimeout in standard PHP, there are obscure ways to implement non-blocking code in parallel with the event loop. We can use functions such as stream_select to create non-blocking network IOs. We can use C extensions like EIO to create non-blocking file system code. Let's take a look at the library built on these obscure methods...

Icicle

Icicle is a component library that takes into account event loops. Let's look at a simple example:

function setTimeout(callable $callback, $delay) {
    $now = microtime(true);

    while (true) {
        if (microtime(true) - $now > $delay) {
            $callback();
            return;
        }
    }
}

setTimeout(function() {
    print "inside the timeout";
}, 1);

print "outside the timeout";
Copy after login

This is using icicleio/icicle version 0.8.0

Icicle's event loop implementation is great. It also has many other impressive features; such as A promise, socket, and server implementation.

Icicle also uses generators as coroutines. Generators and coroutines are a different topic, but the code they allow is beautiful:

use Icicle\Loop;

Loop\timer(0.1, function() {
    print "inside timer";
});

print "outside timer";

Loop\run();
Copy after login

This is using the icicleio/dns version 0.5.0 generator to make writing asynchronous code similar to synchronous code easier. When combined with promises and event loops, they produce excellent non-blocking code like this!

ReactPHP

ReactPHP has a similar event loop implementation, but without all the interesting generator content:

function fitToScreen(selector) {
    var element = document.querySelector(selector);

    var width = element.offsetWidth;
    var height = element.offsetHeight;

    var top = "-" + (height / 2) + "px";
    var left = "-" + (width / 2) + "px";

    var ratio = getRatio(width, height);

    setStyles(element, {
        "position": "absolute",
        "left": "50%",
        "top": "50%",
        "margin": top + " 0 0 " + left,
        "transform": "scale(" + ratio + ", " + ratio + ")"
    });
}

function getRatio(width, height) {
    return Math.min(
        document.body.offsetWidth / width,
        document.body.offsetHeight / height
    );
}

function setStyles(element, styles) {
    for (var key in styles) {
        if (element.style.hasOwnProperty(key)) {
            element.style[key] = styles[key];
        }
    }
}

fitToScreen(".welcome-screen");
Copy after login
Copy after login
Copy after login

This is using react/event-loop version 0.4.1

ReactPHP is more mature than Icicle and has a wider range of components. Icicle still has a long way to go to compete with all the features ReactPHP offers. However, developers are making good progress!

Conclusion

It is difficult to get rid of the single-threaded mindset we were taught to have. If we have access to non-blocking APIs and event loops, we don't know how much code we can write.

The PHP community needs to understand this architecture. We need to learn and experiment with asynchronous and parallel execution. We need to steal these concepts and best practices from other languages ​​that have had event loops for years until “How to use the most system resources effectively?” becomes an easy question to answer with PHP.

Stay tuned for a more practical implementation of the upcoming Icicle!

PHP Event Loop FAQ

What is the role of event loops in PHP?

Event loops in PHP are programming structures used to wait for events or messages in a scheduler. It works by tracking every active event in response to external stimuli and scheduling them when they are finished. This is especially useful in PHP for handling asynchronous operations, where you want to start the operation and then continue processing without waiting for the operation to complete.

How is the difference between event loops and traditional PHP programming?

Traditional PHP programming is synchronous, which means it performs one operation at a time, in the order it was written, and must wait for each operation to complete before continuing with the next operation. On the other hand, event loops allow asynchronous programming. This means that the action can be started and then put it on hold until the result is ready, during which other actions can be performed.

How to implement event loops in my PHP application?

Implementing event loops in your PHP application involves using libraries that provide this functionality, such as ReactPHP or Amp. These libraries provide the necessary interfaces and classes to create and manage event loops. You can then use this event loop to handle asynchronous tasks in your application.

What are the benefits of using PHP event loops?

Using event loops in PHP can greatly improve application performance and responsiveness. It allows you to process multiple tasks simultaneously, rather than sequentially, which can lead to better utilizing resources and shorter response times. This is especially advantageous in applications that require handling a large number of concurrent connections, such as chat servers or real-time data feeds.

What are the disadvantages of using PHP event loops?

While event loops can provide significant performance benefits, they can also increase the complexity of the application. They require different programming styles and may make the code more difficult to understand and debug. Furthermore, not all tasks are suitable for asynchronous processing, and some tasks may be more difficult to implement in event loops.

Can I use event loops with PHP frameworks like Laravel or Symfony?

Yes, event loops can be used with PHP frameworks like Laravel or Symfony, although this may require some additional configuration. Both frameworks are designed to work with synchronous PHP code, but they can be adapted to work with event loops to handle asynchronous tasks.

How to handle errors in the event loop?

Error handling in event loops may be more complicated than error handling in synchronized PHP code. Since the task is executed asynchronously, the error may not be caught immediately. Instead, you usually need to provide a callback function that will be called when an error occurs.

Can I use event loops in PHP CLI scripts?

Yes, you can use event loops in PHP CLI (command line interface) scripts. In fact, this is a common use case for event loops, because CLI scripts often require multiple tasks to be executed simultaneously.

How does event loop work with PHP's garbage collection?

PHP's garbage collection works independently of event loops. However, since the event loop retains references to all active tasks, these tasks will only be garbage collected after completion. This means you need to be careful to avoid memory leaks in event loop code.

Can I use event loops with PHP's built-in server?

Yes, you can use event loops with PHP's built-in server. However, remember that a built-in server is not designed for production purposes and may not provide the same level of performance or reliability as a dedicated web server.

The above is the detailed content of An Introduction into Event Loops in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template