PHP code example of jerome / matrix

1. Go to this page and download the library: Download jerome/matrix library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jerome / matrix example snippets


use Matrix\AsyncHelper;
use function Matrix\async;

// Execute an asynchronous task with success and error handling
async(fn () => 'Task result')
    ->then(function ($result) {
        echo $result; // Output: Task result
    })
    ->catch(function ($e) {
        echo $e->getMessage(); // Handle any errors
    });

async(fn () => throw new \RuntimeException('Error occurred'))
    ->catch(function ($e) {
        echo "Caught error: " . $e->getMessage(); // Output: Caught error: Error occurred
    });

use Matrix\Task;

// Define a task that performs an operation
$task = new Task(function () {
    for ($i = 0; $i < 3; $i++) {
        echo "Working...\n";
        \Fiber::suspend(); // Pause execution and yield control
    }
    return "Task completed";
});

// Start the task
$task->start();

// Resume the task until it completes
while (!$task->isCompleted()) {
    $task->resume();
}

echo $task->getResult(); // Output: Task completed

$task->pause(); // Pause the task
$task->resume(); // Resume the task

use Matrix\Task;
use Matrix\Exceptions\Handler;

// Define an error handler
$errorHandler = new Handler(3, [\RuntimeException::class]);

// Create a task that throws an exception
$task = new Task(function () {
    throw new \RuntimeException('Something went wrong');
}, $errorHandler);

try {
    $task->start();
} catch (\Throwable $e) {
    $errorHandler->handle('task_1', $task, $e);
}

// Retry the task if it failed
if ($task->getStatus() === TaskStatus::FAILED) {
    $task->retry();
}