PHP Luminova: PHP Fiber Asynchronous Tasks and Execution
The Async class leverages PHP's `Fiber` to execute tasks asynchronously, allowing easy concurrent jobs management. It provides methods for queuing, running, and awaiting the completion of tasks.
The Async class in Luminova provides a way to handle asynchronous task execution using PHP Fiber. This allows for better concurrency management, enabling non-blocking operations without relying on traditional threading or external systems. With Fiber, tasks can be suspended and resumed, making it possible to execute multiple operations simultaneously in an efficient, lightweight manner.
It provides methods for queuing, running, and awaiting the completion of tasks and control asynchronous operations, yielding control to other tasks when necessary and continuing execution when the task is completed.
Base Usage
Below are examples of how to initialize and use it effectively:
Task Initialization
Direct Task Execution:
With callable tasks.
$async = Async::task([
new Fiber(fn() => 'Task 1 completed'),
function () { return 'Task 2 completed'; }
]);Instance-Based Task Management:
With Fiber tasks.
$async = new Async([
function () { return 'Task 1 completed'; },
function () { return 'Task 2 completed'; }
]);Awaiting a Single Task:
use Luminova\Http\Network;
$results = Async::await(new Fiber(fn() => Network::get('https://example.com')));
echo $results->getBody()->getContents();Another example:
use Luminova\Http\Network;
$results = Async::await(fn() => Network::get('https://example.com'));
echo $results->getBody()->getContents();Controlled Execution with run
Control the execution flow and yielding of tasks.
$async->enqueue(function () {
echo "Task 1 started\n";
Async::next(); // Yield control to other tasks
echo "Task 1 resumed after yielding\n";
return "Result of Task 1";
});
$async->enqueue(function () {
echo "Task 2 started\n";
Async::sleep(1); // Simulate an asynchronous delay of 1 second
echo "Task 2 completed\n";
return "Result of Task 2";
});
$async->run(function (mixed $result, string|int $id) {
var_dump($result);
});Class Definition
- Class namespace:
Luminova\Components\Async
Properties
result
Executed tasks result.
/**
* @var array<string, mixed>
*/
protected array $result = [];tasks
Array of Fiber or callable tasks to enqueued for execution.
/**
* @var array<string|int, \Fiber|callable>
*/
protected array $tasks = [];Methods
constructor
Initializes a new Async instance with an optional array of tasks.
This constructor initializes the Async instance, optionally accepting an array of tasks (either Fiber or callable) to populate the task queue. If no tasks are provided, an empty queue is initialized.
public function __construct(array $tasks = [])Parameters:
| Parameter | Type | Description |
|---|---|---|
$tasks | array<string|int,Fiber|(callable():mixed)> | An optional array of tasks (Fiber or callable) to initialize the queue with (default []). |
getTasks
Gets the current list of tasks.
public function getTasks(): arrayReturn:
array<int|string,Fiber|callable> - Return an array of current tasks.
getResult
Get executed task result.
public function getResult(): arrayReturn:
array<int|string,mixed> - Return array of completed task results.
isEmpty
Checks whether the task queue is empty.
public function isEmpty(): boolReturn:
bool - Returns true when the queue contains no tasks.
task
Creates a new instance of the Async class, optionally initializing with an array of tasks.
This method allows you to create an Async instance, optionally passing an array of tasks (either Fiber or callable) to initialize the queue. If no tasks are provided, an empty queue will be created.
public static function task(array $tasks = []): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$tasks | array<string|int,Fiber|(callable():mixed)> | An optional array of tasks (Fiber or callable) to initialize with. |
Return:
self - Returns a new instance of the Async class.
Example:
$async = Async::task([
function () { return 'Task 1 completed'; },
function () { return 'Task 2 completed'; }
]);clear
Clears all tasks from the task queue.
public function clear(): boolReturn:
bool - Always return true.
run
Runs all enqueued tasks asynchronously. The run method allows you to control the execution flow of enqueued tasks, including support for yielding and delays.
public function run(?callable $callback = null, float|int $delay = 0.05): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | ?callable | Optional callback to execute with each result. Callback signature: function(mixed $result,int $tid): void} (default null). |
$delay | float|int | Optional delay, the number of seconds to wait after checking for completed task (default: 5000). |
Throws:
- Luminova\Exceptions\RuntimeException - If the method is called while another task execution (
runoruntil) is in progress.
Examples:
use Luminova\Http\Network;
use Psr\Http\Message\ResponseInterface;
$results = [];
$async->enqueue(fn() => Network::get('https://example.com'));
$async->enqueue(fn() => Network::get('https://another.com'));
$async->run(function(ResponseInterface $response, string $id) use(&$results) {
$results[$id] = $response->getBody()->getContents();
});until
Runs the task queue until it is empty.
The method uses the same queue runner as run() with a zero-second delay between passes.
public function until(?callable $callback = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | ?callable | Optional callback to execute after each task completes, receiving the result and index. Callback signature: function(mixed $result,int $tid): void}. |
Throws:
- Luminova\Exceptions\RuntimeException - If the method is called while another task execution (
runoruntil) is in progress.
Examples:
use Luminova\Http\Network;
use Psr\Http\Message\ResponseInterface;
$async->enqueue(fn() => Network::get('https://example.com')
->getBody()
->getContents());
$async->enqueue(fn() => Network::get('https://another.com')
->getBody()
->getContents());
$async->until(function(mixed $result, string $id){
var_dump($result);
});enqueue
Adds a fiber or callable to the task queue for later execution.
public function enqueue(Fiber|callable $task): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$task | Fiber|callable | The task to add to queue (e.g, fiber or callable). |
Return:
string - Return the unique task ID for reference.
dequeue
Removes a task from the task queue by its ID or index.
public function dequeue(string|int $id): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string|int | The task ID or index to remove. |
Return:
bool - Return true if the task was removed, false otherwise.
reindex
Reindexes the tasks array to remove any gaps in the array keys.
This method is useful after tasks have been removed from the queue,ensuring that the remaining tasks are indexed sequentially.
public function reindex(): boolReturn:
bool - Returns true if the reindexed, otherwise false.
prioritize
Prioritizes a specific task by moving it to the front of the queue.
public function prioritize(string|int $id): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string|int | The id or index of the task to prioritize. |
Return:
bool - Return true if the task was prioritized, false otherwise.
next
Suspends the current fiber and yields a value.
If fibers are supported, it suspends the current fiber and yields the given value.If not, it simply returns the value immediately.
public static function next(mixed $value = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to yield. |
Return:
mixed - Returns the value passed back when the suspended Fiber resumes. Call this from inside a Fiber.
sleep
Pauses the execution of the current fiber for a specified duration.
The delay is specified in seconds and can be an integer or a float for precise timing. While paused, other fibers can continue executing.
public static function sleep(float|int $seconds = 0.5): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$seconds | float|int | The duration to pause, in seconds (e.g., 1 for one second, 0.5 for half a second). |
async
Starts an awaitable task and returns its handle. Call await() to retrieve the result. A callable uses a Fiber by default. With $detach enabled, callable tasks use the process-future path.
public static function async(AwaitableInterface|Fiber|callable $task, bool $detach = false): AwaitableInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$task | AwaitableInterface|Fiber|callable | Task to execute asynchronously. |
$detach | bool | Whether callable tasks should execute in a detached background worker process. |
Return:
AwaitableInterface - An awaitable task representing the execution result.
Example:
$future = Async::async(fn(): mixed => doSomething());
$result = Async::await($future);
echo $result;await
Wait for a task to complete and return its result.
Accepts an awaitable handle, Fiber, or callable. When awaiting from the main execution context, use an awaitable handle for tasks that suspend or need multiple execution ticks.
Throws if the task does not complete in time or if the task itself fails.
public static function await(AwaitableInterface|Fiber|callable $task, int $timeout = 0, float|int $delay = 0.1): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$task | AwaitableInterface|Fiber|callable | The task to await (e.g, Fiber or callable).If a callable is provided, it will be wrapped in a Fiber. |
$timeout | int | Maximum wait time in seconds (0 = unlimited) (default 0). |
$delay | float|int | Delay in seconds between execution ticks (default 0.1). |
Return:
mixed - Return the value returned by the task upon completion.
Throws:
- Luminova\Exceptions\RuntimeException - If the task does not complete within $timeout seconds.
Throwable- If the underlying task fails and its error propagates.
Example:
use Luminova\Http\Network;
use Psr\Http\Message\ResponseInterface;
$requests = [
fn() => Network::get('https://example.com'),
fn() => Network::get('https://another.com'),
];
$results = [];
foreach ($requests as $request) {
$response = Async::await($request);
$results[] = ($response instanceof ResponseInterface)
? $response->getBody()->getContents()
: $response;
}
print_r($results);Using Async Helper Method:
$future = Async::async(fn() => doSomething());
$result = Async::await($future);
echo $result;With delay:
Async::await(Async::async(fn() => doWork()), delay: 0.01);With timeout:
try {
Async::await(Async::async(fn() => slowTask()), timeout: 2);
} catch (\Luminova\Exceptions\RuntimeException $e) {
echo "Task timed out!";
}setTimeout
Executes a given callback function after a specified timeout in seconds.
The method waits before running the callback and returns after it finishes. Callback failures are wrapped in a RuntimeException.
public static function setTimeout(callable $callback, float|int $seconds): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | callable | The callback function to execute after the timeout. |
$seconds | float|int | The delay before the callback is executed, in seconds. |
Throws:
- Luminova\Exceptions\RuntimeException - Throws if an error occurs during execution.
Example:
Async::setTimeout(function () {
echo "Timeout executed at: " . date('H:i:s') . "\n";
}, 2);timeout
Creates a Fiber to execute a given callback after a specified timeout.
The returned Fiber is already started and suspended. Resume it to wait for the delay and run the callback.
public static function timeout(callable $callback, float|int $seconds): FiberParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | callable | The callback function to execute after the timeout. |
$seconds | float|int | The delay before the callback is executed, in seconds. |
Return:
Fiber - Return the Fiber instance for managing the timeout execution.
Throws:
- Luminova\Exceptions\RuntimeException - Throws if an error occurs during execution.
Example:
echo "Start\n";
$fiber = Async::timeout(function () {
echo "Timeout executed in fiber at: " . date('H:i:s') . "\n";
}, 2);
// Simulate 1 second of work
usleep(1000_000);
// Resume the fiber to allow the callback to execute
$fiber->resume();
echo "End\n";Another Example:
$fibers = [];
$fibers[] = Async::timeout(function () {
echo "Task 1 executed after 1 second\n";
}, 1);
$fibers[] = Async::timeout(function () {
echo "Task 2 executed after 2 seconds\n";
}, 2);
foreach ($fibers as $fiber) {
$fiber->resume();
}background
Create an awaitable handle for background work. Under the CLI runtime, the process future invokes the task in the current process. In web requests, it uses a PHP worker process.
public static function background(
callable|string $task,
array $arguments = [],
bool $autoStart = true,
bool $awaitable = false,
?string $phpPath = null
): AwaitableInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$task | callable|string | Callable to run, or a string containing PHP code without opening tags. |
$arguments | array<string|int,mixed> | Arguments passed to the worker (default []). |
$autoStart | bool | Whether to delay execution until AwaitableInterface::start() is called (default true). |
$awaitable | bool | Whether to capture a result for later retrieval (default false). |
$phpPath | ?string | Optional PHP CLI binary path (default null). |
Return:
AwaitableInterface - Returns a process future for the task.
Example:
Capture a task’s output in a CLI command.
use Luminova\Components\Async;
$future = Async::background(
function (): void {
echo 42;
},
autoStart: false,
awaitable: true
);
echo Async::await($future); // 42