Convert Figma logo to code with AI

reactphp logoevent-loop

ReactPHP's core reactor event loop that libraries can use for evented I/O.

1,239
126
1,239
4

Top Related Projects

4,217

A non-blocking concurrency framework for PHP applications. 🐘

24,093

Cross-platform asynchronous I/O

106,466

Node.js JavaScript runtime ✨🐢🚀✨

Provides tools that allow your application components to communicate with each other by dispatching events and listening to them

32,329

The Laravel Framework.

23,156

Guzzle, an extensible PHP HTTP client

Quick Overview

ReactPHP's Event Loop is a core component of the ReactPHP ecosystem, providing a powerful and efficient event-driven programming model for PHP applications. It allows developers to handle asynchronous operations, manage timers, and process I/O events in a non-blocking manner, enabling the creation of high-performance, scalable applications.

Pros

  • Lightweight and efficient implementation of the event loop concept
  • Seamless integration with other ReactPHP components
  • Supports multiple event loop implementations (e.g., ExtEventLoop, StreamSelectLoop)
  • Enables writing non-blocking, asynchronous PHP applications

Cons

  • Requires a shift in programming paradigm for developers used to synchronous code
  • Limited native support for multi-threading in PHP
  • May have a steeper learning curve compared to traditional PHP programming
  • Performance can vary depending on the chosen event loop implementation

Code Examples

  1. Basic usage of the event loop:
$loop = React\EventLoop\Loop::get();

$loop->addTimer(1.0, function () {
    echo "Hello after 1 second!\n";
});

$loop->run();
  1. Periodic timer example:
$loop = React\EventLoop\Loop::get();

$timer = $loop->addPeriodicTimer(0.1, function () {
    echo "Tick\n";
});

$loop->addTimer(1.0, function () use ($loop, $timer) {
    $loop->cancelTimer($timer);
});

$loop->run();
  1. Handling signals:
$loop = React\EventLoop\Loop::get();

$loop->addSignal(SIGINT, function (int $signal) use ($loop) {
    echo "Caught SIGINT, stopping loop.\n";
    $loop->stop();
});

$loop->run();

Getting Started

To start using ReactPHP's Event Loop, first install it via Composer:

composer require react/event-loop

Then, in your PHP script:

<?php

require 'vendor/autoload.php';

$loop = React\EventLoop\Loop::get();

// Add your event listeners and timers here

$loop->run();

This sets up the event loop and runs it. You can now add timers, I/O events, and other asynchronous operations to create your reactive application.

Competitor Comparisons

4,217

A non-blocking concurrency framework for PHP applications. 🐘

Pros of amp

  • Built-in support for coroutines, making asynchronous code more readable
  • Integrated promise implementation optimized for performance
  • Comprehensive ecosystem with additional libraries for HTTP, WebSockets, and more

Cons of amp

  • Steeper learning curve due to its unique approach to concurrency
  • Smaller community compared to ReactPHP, potentially leading to fewer resources and third-party packages

Code Comparison

amp:

\Amp\Loop::run(function () {
    $response = yield \Amp\Http\Client\HttpClientBuilder::buildDefault()
        ->request('https://example.com');
    echo yield $response->getBody()->buffer();
});

event-loop:

$loop = \React\EventLoop\Factory::create();
$browser = new \React\Http\Browser($loop);
$browser->get('https://example.com')->then(function ($response) {
    echo $response->getBody();
});
$loop->run();

Key Differences

  • amp uses coroutines with yield for asynchronous operations, while event-loop relies on callbacks and promises
  • amp's ecosystem is more tightly integrated, whereas event-loop is part of the broader ReactPHP ecosystem
  • amp focuses on high-performance async programming, while event-loop aims for simplicity and compatibility with other ReactPHP components

Both libraries provide robust solutions for asynchronous programming in PHP, with amp offering a more opinionated approach and event-loop providing flexibility within the ReactPHP ecosystem.

24,093

Cross-platform asynchronous I/O

Pros of libuv

  • Written in C, offering better performance and lower-level system access
  • Supports a wider range of platforms, including Windows
  • More comprehensive feature set, including file system operations and network protocols

Cons of libuv

  • Steeper learning curve due to C programming and lower-level abstractions
  • Requires compilation and may introduce platform-specific complexities
  • Less idiomatic for PHP developers compared to ReactPHP

Code Comparison

ReactPHP event-loop:

$loop = React\EventLoop\Factory::create();
$loop->addTimer(1.0, function () {
    echo "Hello World\n";
});
$loop->run();

libuv:

uv_loop_t *loop = malloc(sizeof(uv_loop_t));
uv_loop_init(loop);
uv_timer_t timer;
uv_timer_init(loop, &timer);
uv_timer_start(&timer, timer_cb, 1000, 0);
uv_run(loop, UV_RUN_DEFAULT);

Summary

libuv is a powerful, cross-platform library for asynchronous I/O, offering high performance and a wide range of features. It's suitable for building low-level, high-performance applications. ReactPHP event-loop, on the other hand, provides a more PHP-friendly abstraction, making it easier for PHP developers to work with asynchronous programming patterns. The choice between the two depends on the specific project requirements, performance needs, and the development team's expertise.

106,466

Node.js JavaScript runtime ✨🐢🚀✨

Pros of Node.js

  • Larger ecosystem with more packages and community support
  • Better performance for I/O-intensive operations
  • Native support for JavaScript, making it easier for front-end developers to transition

Cons of Node.js

  • Heavier and more resource-intensive than ReactPHP
  • Less flexibility in choosing the event loop implementation
  • Steeper learning curve for PHP developers

Code Comparison

ReactPHP Event Loop:

$loop = React\EventLoop\Factory::create();
$loop->addTimer(1.0, function () {
    echo "Hello World\n";
});
$loop->run();

Node.js:

setTimeout(() => {
  console.log("Hello World");
}, 1000);

Both examples demonstrate a simple timer-based operation, showcasing the event loop functionality. ReactPHP requires explicit creation and running of the event loop, while Node.js handles this implicitly.

ReactPHP Event Loop is a lightweight, PHP-based event loop library, while Node.js is a full-fledged JavaScript runtime environment. ReactPHP offers more flexibility and is easier to integrate into existing PHP projects, whereas Node.js provides a more comprehensive ecosystem and better performance for certain types of applications.

The choice between the two depends on the specific project requirements, existing technology stack, and developer expertise. ReactPHP is ideal for adding asynchronous capabilities to PHP applications, while Node.js is better suited for building scalable network applications from the ground up.

Provides tools that allow your application components to communicate with each other by dispatching events and listening to them

Pros of Event Dispatcher

  • Part of the larger Symfony ecosystem, offering seamless integration with other Symfony components
  • Provides a more traditional event-driven programming model, familiar to many PHP developers
  • Offers a simpler API for basic event handling and dispatching

Cons of Event Dispatcher

  • Less suited for asynchronous programming and I/O operations compared to Event Loop
  • May have higher overhead for high-frequency event dispatching scenarios
  • Limited built-in support for timers and periodic tasks

Code Comparison

Event Dispatcher:

$dispatcher = new EventDispatcher();
$dispatcher->addListener('foo.action', function (Event $event) {
    // Event handler logic
});
$dispatcher->dispatch('foo.action', new Event());

Event Loop:

$loop = Factory::create();
$loop->addTimer(0.1, function () {
    // Timer callback logic
});
$loop->run();

The Event Dispatcher focuses on dispatching and handling custom events, while Event Loop provides a more comprehensive solution for managing asynchronous operations, including timers and I/O events. Event Loop is better suited for building reactive, non-blocking applications, whereas Event Dispatcher excels in traditional event-driven architectures within the Symfony framework.

32,329

The Laravel Framework.

Pros of Laravel Framework

  • Comprehensive full-stack framework with built-in features for routing, ORM, authentication, and more
  • Extensive ecosystem with a large community and many packages available
  • Elegant syntax and developer-friendly conventions for rapid application development

Cons of Laravel Framework

  • Heavier and more resource-intensive compared to the lightweight event loop library
  • Steeper learning curve for beginners due to its extensive feature set
  • May be overkill for simple applications or microservices

Code Comparison

Laravel Framework:

Route::get('/users', function () {
    return User::all();
});

ReactPHP Event Loop:

$loop = React\EventLoop\Factory::create();
$loop->addTimer(1.0, function () {
    echo "Hello World\n";
});
$loop->run();

Summary

Laravel Framework is a full-featured PHP web application framework, while ReactPHP Event Loop is a lightweight library focused on asynchronous programming. Laravel offers a complete solution for web development with many built-in features, while ReactPHP Event Loop provides a foundation for building event-driven applications. The choice between them depends on the project requirements, with Laravel being more suitable for complex web applications and ReactPHP Event Loop better for applications requiring high concurrency and low-level control over I/O operations.

23,156

Guzzle, an extensible PHP HTTP client

Pros of Guzzle

  • Comprehensive HTTP client with a user-friendly API
  • Extensive documentation and community support
  • Built-in support for various authentication methods and request/response plugins

Cons of Guzzle

  • Heavier and more feature-rich, which may be overkill for simple HTTP requests
  • Not specifically designed for asynchronous programming or event-driven architecture

Code Comparison

ReactPHP Event Loop:

$loop = React\EventLoop\Factory::create();
$loop->addTimer(1.0, function () {
    echo "Hello World\n";
});
$loop->run();

Guzzle:

$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.example.com');
echo $response->getBody();

Summary

ReactPHP Event Loop and Guzzle serve different purposes in PHP development. ReactPHP Event Loop focuses on providing an event-driven programming model for asynchronous operations, while Guzzle is a feature-rich HTTP client for making web requests.

ReactPHP Event Loop is lightweight and ideal for building scalable, non-blocking applications. It's particularly useful for long-running processes or applications that need to handle multiple concurrent operations efficiently.

Guzzle, on the other hand, excels at simplifying HTTP requests and responses. It offers a wide range of features out of the box, making it an excellent choice for projects that require extensive HTTP functionality without the need for low-level event handling.

Choose ReactPHP Event Loop for event-driven, asynchronous programming, and Guzzle for comprehensive HTTP client capabilities in more traditional PHP applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

EventLoop

CI status installs on Packagist

ReactPHP's core reactor event loop that libraries can use for evented I/O.

Development version: This branch contains the code for the upcoming v3 release. For the code of the current stable v1 release, check out the 1.x branch.

The upcoming v3 release will be the way forward for this package. However, we will still actively support v1 for those not yet on the latest version. See also installation instructions for more details.

In order for async based libraries to be interoperable, they need to use the same event loop. This component provides a common LoopInterface that any library can target. This allows them to be used in the same loop, with one single run() call that is controlled by the user.

Table of contents

Quickstart example

Here is an async HTTP server built with just the event loop.

<?php

use React\EventLoop\Loop;

require __DIR__ . '/vendor/autoload.php';

$server = stream_socket_server('tcp://127.0.0.1:8080');
stream_set_blocking($server, false);

Loop::addReadStream($server, function ($server) {
    $conn = stream_socket_accept($server);
    $data = "HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nHi\n";
    Loop::addWriteStream($conn, function ($conn) use (&$data) {
        $written = fwrite($conn, $data);
        if ($written === strlen($data)) {
            fclose($conn);
            Loop::removeWriteStream($conn);
        } else {
            $data = substr($data, $written);
        }
    });
});

Loop::addPeriodicTimer(5, function () {
    $memory = memory_get_usage() / 1024;
    $formatted = number_format($memory, 3).'K';
    echo "Current memory usage: {$formatted}\n";
});

See also the examples.

Usage

Typical applications would use the Loop class to use the default event loop like this:

use React\EventLoop\Loop;

$timer = Loop::addPeriodicTimer(0.1, function () {
    echo 'Tick' . PHP_EOL;
});

Loop::addTimer(1.0, function () use ($timer) {
    Loop::cancelTimer($timer);
    echo 'Done' . PHP_EOL;
});

As an alternative, you can also explicitly create an event loop instance at the beginning, reuse it throughout your program and finally run it at the end of the program like this:

$loop = React\EventLoop\Loop::get();

$timer = $loop->addPeriodicTimer(0.1, function () {
    echo 'Tick' . PHP_EOL;
});

$loop->addTimer(1.0, function () use ($loop, $timer) {
    $loop->cancelTimer($timer);
    echo 'Done' . PHP_EOL;
});

$loop->run();

While the former is more concise, the latter is more explicit. In both cases, the program would perform the exact same steps.

  1. The event loop instance is created at the beginning of the program. This is implicitly done the first time you call the Loop class (or by manually instantiating any of the loop implementations).
  2. The event loop is used directly or passed as an instance to library and application code. In this example, a periodic timer is registered with the event loop which simply outputs Tick every fraction of a second until another timer stops the periodic timer after a second.
  3. The event loop is run at the end of the program. This is automatically done when using the Loop class or explicitly with a single run() call at the end of the program.

As of v1.2.0, we highly recommend using the Loop class. The explicit loop instructions are still valid and may still be useful in some applications, especially for a transition period towards the more concise style.

Loop

The Loop class exists as a convenient global accessor for the event loop.

Loop methods

The Loop class provides all methods that exist on the LoopInterface as static methods:

If you're working with the event loop in your application code, it's often easiest to directly interface with the static methods defined on the Loop class like this:

use React\EventLoop\Loop;

$timer = Loop::addPeriodicTimer(0.1, function () {
    echo 'Tick' . PHP_EOL;
});

Loop::addTimer(1.0, function () use ($timer) {
    Loop::cancelTimer($timer);
    echo 'Done' . PHP_EOL;
});

On the other hand, if you're familiar with object-oriented programming (OOP) and dependency injection (DI), you may want to inject an event loop instance and invoke instance methods on the LoopInterface like this:

use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;

class Greeter
{
    private $loop;

    public function __construct(LoopInterface $loop)
    {
        $this->loop = $loop;
    }

    public function greet(string $name)
    {
        $this->loop->addTimer(1.0, function () use ($name) {
            echo 'Hello ' . $name . '!' . PHP_EOL;
        });
    }
}

$greeter = new Greeter(Loop::get());
$greeter->greet('Alice');
$greeter->greet('Bob');

Each static method call will be forwarded as-is to the underlying event loop instance by using the Loop::get() call internally. See LoopInterface for more details about available methods.

Loop autorun

When using the Loop class, it will automatically execute the loop at the end of the program. This means the following example will schedule a timer and will automatically execute the program until the timer event fires:

use React\EventLoop\Loop;

Loop::addTimer(1.0, function () {
    echo 'Hello' . PHP_EOL;
});

As of v1.2.0, we highly recommend using the Loop class this way and omitting any explicit run() calls. For BC reasons, the explicit run() method is still valid and may still be useful in some applications, especially for a transition period towards the more concise style.

If you don't want the Loop to run automatically, you can either explicitly run() or stop() it. This can be useful if you're using a global exception handler like this:

use React\EventLoop\Loop;

Loop::addTimer(10.0, function () {
    echo 'Never happens';
});

set_exception_handler(function (Throwable $e) {
    echo 'Error: ' . $e->getMessage() . PHP_EOL;
    Loop::stop();
});

throw new RuntimeException('Demo');

get()

The get(): LoopInterface method can be used to get the currently active event loop instance.

This method will always return the same event loop instance throughout the lifetime of your application.

use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;

$loop = Loop::get();

assert($loop instanceof LoopInterface);
assert($loop === Loop::get());

This is particularly useful if you're using object-oriented programming (OOP) and dependency injection (DI). In this case, you may want to inject an event loop instance and invoke instance methods on the LoopInterface like this:

use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;

class Greeter
{
    private $loop;

    public function __construct(LoopInterface $loop)
    {
        $this->loop = $loop;
    }

    public function greet(string $name)
    {
        $this->loop->addTimer(1.0, function () use ($name) {
            echo 'Hello ' . $name . '!' . PHP_EOL;
        });
    }
}

$greeter = new Greeter(Loop::get());
$greeter->greet('Alice');
$greeter->greet('Bob');

See LoopInterface for more details about available methods.

Loop implementations

In addition to the LoopInterface, there are a number of event loop implementations provided.

All of the event loops support these features:

  • File descriptor polling
  • One-off timers
  • Periodic timers
  • Deferred execution on future loop tick

For most consumers of this package, the underlying event loop implementation is an implementation detail. You should use the Loop class to automatically create a new instance.

Advanced! If you explicitly need a certain event loop implementation, you can manually instantiate one of the following classes. Note that you may have to install the required PHP extensions for the respective event loop implementation first or they will throw a BadMethodCallException on creation.

StreamSelectLoop

A stream_select() based event loop.

This uses the stream_select() function and is the only implementation that works out of the box with PHP.

This event loop works out of the box on any PHP version. This means that no installation is required and this library works on all platforms and supported PHP versions. Accordingly, the Loop class will use this event loop by default if you do not install any of the event loop extensions listed below.

Under the hood, it does a simple select system call. This system call is limited to the maximum file descriptor number of FD_SETSIZE (platform dependent, commonly 1024) and scales with O(m) (m being the maximum file descriptor number passed). This means that you may run into issues when handling thousands of streams concurrently and you may want to look into using one of the alternative event loop implementations listed below in this case. If your use case is among the many common use cases that involve handling only dozens or a few hundred streams at once, then this event loop implementation performs really well.

If you want to use signal handling (see also addSignal() below), this event loop implementation requires ext-pcntl. This extension is only available for Unix-like platforms and does not support Windows. It is commonly installed as part of many PHP distributions. If this extension is missing (or you're running on Windows), signal handling is not supported and throws a BadMethodCallException instead.

This event loop is known to rely on wall-clock time to schedule future timers when using any version before PHP 7.3, because a monotonic time source is only available as of PHP 7.3 (hrtime()). While this does not affect many common use cases, this is an important distinction for programs that rely on a high time precision or on systems that are subject to discontinuous time adjustments (time jumps). This means that if you schedule a timer to trigger in 30s on PHP < 7.3 and then adjust your system time forward by 20s, the timer may trigger in 10s. See also addTimer() for more details.

ExtEventLoop

An ext-event based event loop.

This uses the event PECL extension, that provides an interface to libevent library. libevent itself supports a number of system-specific backends (epoll, kqueue).

This loop is known to work with PHP 7.1 through PHP 8+.

ExtEvLoop

An ext-ev based event loop.

This loop uses the ev PECL extension, that provides an interface to libev library. libev itself supports a number of system-specific backends (epoll, kqueue).

This loop is known to work with PHP 7.1 through PHP 8+.

ExtUvLoop

An ext-uv based event loop.

This loop uses the uv PECL extension, that provides an interface to libuv library. libuv itself supports a number of system-specific backends (epoll, kqueue).

This loop is known to work with PHP 7.1 through PHP 8+.

LoopInterface

run()

The run(): void method can be used to run the event loop until there are no more tasks to perform.

For many applications, this method is the only directly visible invocation on the event loop. As a rule of thumb, it is usually recommended to attach everything to the same loop instance and then run the loop once at the bottom end of the application.

$loop->run();

This method will keep the loop running until there are no more tasks to perform. In other words: This method will block until the last timer, stream and/or signal has been removed.

Likewise, it is imperative to ensure the application actually invokes this method once. Adding listeners to the loop and missing to actually run it will result in the application exiting without actually waiting for any of the attached listeners.

This method MUST NOT be called while the loop is already running. This method MAY be called more than once after it has explicitly been stop()ped or after it automatically stopped because it previously did no longer have anything to do.

stop()

The stop(): void method can be used to instruct a running event loop to stop.

This method is considered advanced usage and should be used with care. As a rule of thumb, it is usually recommended to let the loop stop only automatically when it no longer has anything to do.

This method can be used to explicitly instruct the event loop to stop:

$loop->addTimer(3.0, function () use ($loop) {
    $loop->stop();
});

Calling this method on a loop instance that is not currently running or on a loop instance that has already been stopped has no effect.

addTimer()

The addTimer(float $interval, callable $callback): TimerInterface method can be used to enqueue a callback to be invoked once after the given interval.

The second parameter MUST be a timer callback function that accepts the timer instance as its only parameter. If you don't use the timer instance inside your timer callback function you MAY use a function which has no parameters at all.

The timer callback function MUST NOT throw an Exception. The return value of the timer callback function will be ignored and has no effect, so for performance reasons you're recommended to not return any excessive data structures.

This method returns a timer instance. The same timer instance will also be passed into the timer callback function as described above. You can invoke cancelTimer to cancel a pending timer. Unlike addPeriodicTimer(), this method will ensure the callback will be invoked only once after the given interval.

$loop->addTimer(0.8, function () {
    echo 'world!' . PHP_EOL;
});

$loop->addTimer(0.3, function () {
    echo 'hello ';
});

See also example #1.

If you want to access any variables within your callback function, you can bind arbitrary data to a callback closure like this:

function hello($name, LoopInterface $loop)
{
    $loop->addTimer(1.0, function () use ($name) {
        echo "hello $name\n";
    });
}

hello('Tester', $loop);

This interface does not enforce any particular timer resolution, so special care may have to be taken if you rely on very high precision with millisecond accuracy or below. Event loop implementations SHOULD work on a best effort basis and SHOULD provide at least millisecond accuracy unless otherwise noted. Many existing event loop implementations are known to provide microsecond accuracy, but it's generally not recommended to rely on this high precision.

Similarly, the execution order of timers scheduled to execute at the same time (within its possible accuracy) is not guaranteed.

This interface suggests that event loop implementations SHOULD use a monotonic time source if available. Given that a monotonic time source is only available as of PHP 7.3 by default, event loop implementations MAY fall back to using wall-clock time. While this does not affect many common use cases, this is an important distinction for programs that rely on a high time precision or on systems that are subject to discontinuous time adjustments (time jumps). This means that if you schedule a timer to trigger in 30s and then adjust your system time forward by 20s, the timer SHOULD still trigger in 30s. See also event loop implementations for more details.

addPeriodicTimer()

The addPeriodicTimer(float $interval, callable $callback): TimerInterface method can be used to enqueue a callback to be invoked repeatedly after the given interval.

The second parameter MUST be a timer callback function that accepts the timer instance as its only parameter. If you don't use the timer instance inside your timer callback function you MAY use a function which has no parameters at all.

The timer callback function MUST NOT throw an Exception. The return value of the timer callback function will be ignored and has no effect, so for performance reasons you're recommended to not return any excessive data structures.

This method returns a timer instance. The same timer instance will also be passed into the timer callback function as described above. Unlike addTimer(), this method will ensure the callback will be invoked infinitely after the given interval or until you invoke cancelTimer.

$timer = $loop->addPeriodicTimer(0.1, function () {
    echo 'tick!' . PHP_EOL;
});

$loop->addTimer(1.0, function () use ($loop, $timer) {
    $loop->cancelTimer($timer);
    echo 'Done' . PHP_EOL;
});

See also example #2.

If you want to limit the number of executions, you can bind arbitrary data to a callback closure like this:

function hello($name, LoopInterface $loop)
{
    $n = 3;
    $loop->addPeriodicTimer(1.0, function ($timer) use ($name, $loop, &$n) {
        if ($n > 0) {
            --$n;
            echo "hello $name\n";
        } else {
            $loop->cancelTimer($timer);
        }
    });
}

hello('Tester', $loop);

This interface does not enforce any particular timer resolution, so special care may have to be taken if you rely on very high precision with millisecond accuracy or below. Event loop implementations SHOULD work on a best effort basis and SHOULD provide at least millisecond accuracy unless otherwise noted. Many existing event loop implementations are known to provide microsecond accuracy, but it's generally not recommended to rely on this high precision.

Similarly, the execution order of timers scheduled to execute at the same time (within its possible accuracy) is not guaranteed.

This interface suggests that event loop implementations SHOULD use a monotonic time source if available. Given that a monotonic time source is only available as of PHP 7.3 by default, event loop implementations MAY fall back to using wall-clock time. While this does not affect many common use cases, this is an important distinction for programs that rely on a high time precision or on systems that are subject to discontinuous time adjustments (time jumps). This means that if you schedule a timer to trigger in 30s and then adjust your system time forward by 20s, the timer SHOULD still trigger in 30s. See also event loop implementations for more details.

Additionally, periodic timers may be subject to timer drift due to re-scheduling after each invocation. As such, it's generally not recommended to rely on this for high precision intervals with millisecond accuracy or below.

cancelTimer()

The cancelTimer(TimerInterface $timer): void method can be used to cancel a pending timer.

See also addPeriodicTimer() and example #2.

Calling this method on a timer instance that has not been added to this loop instance or on a timer that has already been cancelled has no effect.

futureTick()

The futureTick(callable $listener): void method can be used to schedule a callback to be invoked on a future tick of the event loop.

This works very much similar to timers with an interval of zero seconds, but does not require the overhead of scheduling a timer queue.

The tick callback function MUST be able to accept zero parameters.

The tick callback function MUST NOT throw an Exception. The return value of the tick callback function will be ignored and has no effect, so for performance reasons you're recommended to not return any excessive data structures.

If you want to access any variables within your callback function, you can bind arbitrary data to a callback closure like this:

function hello($name, LoopInterface $loop)
{
    $loop->futureTick(function () use ($name) {
        echo "hello $name\n";
    });
}

hello('Tester', $loop);

Unlike timers, tick callbacks are guaranteed to be executed in the order they are enqueued. Also, once a callback is enqueued, there's no way to cancel this operation.

This is often used to break down bigger tasks into smaller steps (a form of cooperative multitasking).

$loop->futureTick(function () {
    echo 'b';
});
$loop->futureTick(function () {
    echo 'c';
});
echo 'a';

See also example #3.

addSignal()

The addSignal(int $signal, callable $listener): void method can be used to register a listener to be notified when a signal has been caught by this process.

This is useful to catch user interrupt signals or shutdown signals from tools like supervisor or systemd.

The second parameter MUST be a listener callback function that accepts the signal as its only parameter. If you don't use the signal inside your listener callback function you MAY use a function which has no parameters at all.

The listener callback function MUST NOT throw an Exception. The return value of the listener callback function will be ignored and has no effect, so for performance reasons you're recommended to not return any excessive data structures.

$loop->addSignal(SIGINT, function (int $signal) {
    echo 'Caught user interrupt signal' . PHP_EOL;
});

See also example #4.

Signaling is only available on Unix-like platforms, Windows isn't supported due to operating system limitations. This method may throw a BadMethodCallException if signals aren't supported on this platform, for example when required extensions are missing.

Note: A listener can only be added once to the same signal, any attempts to add it more than once will be ignored.

removeSignal()

The removeSignal(int $signal, callable $listener): void method can be used to remove a previously added signal listener.

$loop->removeSignal(SIGINT, $listener);

Any attempts to remove listeners that aren't registered will be ignored.

addReadStream()

Advanced! Note that this low-level API is considered advanced usage. Most use cases should probably use the higher-level readable Stream API instead.

The addReadStream(resource $stream, callable $callback): void method can be used to register a listener to be notified when a stream is ready to read.

The first parameter MUST be a valid stream resource that supports checking whether it is ready to read by this loop implementation. A single stream resource MUST NOT be added more than once. Instead, either call removeReadStream() first or react to this event with a single listener and then dispatch from this listener. This method MAY throw an Exception if the given resource type is not supported by this loop implementation.

The second parameter MUST be a listener callback function that accepts the stream resource as its only parameter. If you don't use the stream resource inside your listener callback function you MAY use a function which has no parameters at all.

The listener callback function MUST NOT throw an Exception. The return value of the listener callback function will be ignored and has no effect, so for performance reasons you're recommended to not return any excessive data structures.

If you want to access any variables within your callback function, you can bind arbitrary data to a callback closure like this:

$loop->addReadStream($stream, function ($stream) use ($name) {
    echo $name . ' said: ' . fread($stream);
});

See also example #11.

You can invoke removeReadStream() to remove the read event listener for this stream.

The execution order of listeners when multiple streams become ready at the same time is not guaranteed.

Some event loop implementations are known to only trigger the listener if the stream becomes readable (edge-triggered) and may not trigger if the stream has already been readable from the beginning. This also implies that a stream may not be recognized as readable when data is still left in PHP's internal stream buffers. As such, it's recommended to use stream_set_read_buffer($stream, 0); to disable PHP's internal read buffer in this case.

addWriteStream()

Advanced! Note that this low-level API is considered advanced usage. Most use cases should probably use the higher-level writable Stream API instead.

The addWriteStream(resource $stream, callable $callback): void method can be used to register a listener to be notified when a stream is ready to write.

The first parameter MUST be a valid stream resource that supports checking whether it is ready to write by this loop implementation. A single stream resource MUST NOT be added more than once. Instead, either call removeWriteStream() first or react to this event with a single listener and then dispatch from this listener. This method MAY throw an Exception if the given resource type is not supported by this loop implementation.

The second parameter MUST be a listener callback function that accepts the stream resource as its only parameter. If you don't use the stream resource inside your listener callback function you MAY use a function which has no parameters at all.

The listener callback function MUST NOT throw an Exception. The return value of the listener callback function will be ignored and has no effect, so for performance reasons you're recommended to not return any excessive data structures.

If you want to access any variables within your callback function, you can bind arbitrary data to a callback closure like this:

$loop->addWriteStream($stream, function ($stream) use ($name) {
    fwrite($stream, 'Hello ' . $name);
});

See also example #12.

You can invoke removeWriteStream() to remove the write event listener for this stream.

The execution order of listeners when multiple streams become ready at the same time is not guaranteed.

removeReadStream()

The removeReadStream(resource $stream): void method can be used to remove the read event listener for the given stream.

Removing a stream from the loop that has already been removed or trying to remove a stream that was never added or is invalid has no effect.

removeWriteStream()

The removeWriteStream(resource $stream): void method can be used to remove the write event listener for the given stream.

Removing a stream from the loop that has already been removed or trying to remove a stream that was never added or is invalid has no effect.

Install

The recommended way to install this library is through Composer. New to Composer?

Once released, this project will follow SemVer. At the moment, this will install the latest development version:

composer require react/event-loop:^3@dev

See also the CHANGELOG for details about version upgrades.

This project aims to run on any platform and thus does not require any PHP extensions and supports running on PHP 7.1 through current PHP 8+. It's highly recommended to use the latest supported PHP version for this project.

Installing any of the event loop extensions is suggested, but entirely optional. See also event loop implementations for more details.

Tests

To run the test suite, you first need to clone this repo and then install all dependencies through Composer:

composer install

To run the test suite, go to the project root and run:

vendor/bin/phpunit

License

MIT, see LICENSE file.

More