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/ */
use function Matrix\{async, await, any};
$promises = [
async(function () { throw new \Exception('Error 1'); }),
async(function () { return 'Success'; }),
async(function () { throw new \Exception('Error 2'); }),
];
$result = await(any($promises));
// $result = 'Success'
use function Matrix\{async, await, map};
$urls = ['https://example.com', 'https://example.org', 'https://example.net'];
$results = await(map(
$urls,
function ($url) {
// Fetch the URL contents asynchronously
return async(function () use ($url) {
$contents = file_get_contents($url);
return strlen($contents);
});
},
2, // Process 2 URLs at a time
function ($done, $total) {
echo "Processed $done of $total URLs\n";
}
));
print_r($results); // Array of content lengths
use function Matrix\{async, await, batch};
$items = range(1, 100); // 100 items to process
$results = await(batch(
$items,
function ($batch) {
return async(function () use ($batch) {
// Process the entire batch at once
return array_map(fn ($item) => $item * 2, $batch);
});
},
25, // 25 items per batch
2 // Process 2 batches concurrently
));
print_r($results); // Array of processed items
use function Matrix\{async, await, timeout};
try {
$result = await(timeout(
async(function () {
sleep(5); // Long operation
return 'Done';
}),
2.0, // 2 second timeout
'The operation took too long'
));
} catch (\Matrix\Exceptions\TimeoutException $e) {
echo $e->getMessage(); // "The operation took too long"
echo "Duration: " . $e->getDuration() . " seconds"; // "Duration: 2 seconds"
}
use function Matrix\{async, await, retry};
try {
$result = await(retry(
function () {
return async(function () {
// Simulate an operation that sometimes fails
if (rand(1, 3) === 1) {
return 'Success';
}
throw new \RuntimeException('Failed');
});
},
5, // Try up to 5 times
function ($attempt, $error) {
// Exponential backoff with jitter
$delay = min(pow(2, $attempt - 1) * 0.1, 5.0) * (0.8 + 0.4 * mt_rand() / mt_getrandmax());
echo "Attempt $attempt failed: {$error->getMessage()}, retrying in {$delay}s...\n";
return $delay; // Return null to stop retrying
}
));
echo "Finally succeeded: $result\n";
} catch (\Matrix\Exceptions\RetryException $e) {
echo "All {$e->getAttempts()} attempts failed\n";
foreach ($e->getFailures() as $index => $failure) {
echo "Failure " . ($index + 1) . ": " . $failure->getMessage() . "\n";
}
}
use function Matrix\{async, await, cancellable};
// Start a long operation
$operation = async(function () {
// Simulate long computation
for ($i = 0; $i < 10; $i++) {
// Check for cancellation at safe points
if (/* cancelled check */) {
throw new \RuntimeException('Operation cancelled');
}
sleep(1);
}
return 'Completed';
});
// Create a clean-up function for when the operation is cancelled
$cleanup = function () {
echo "Cleaning up resources...\n";
// Release any held resources
};
// Create a cancellable promise
$cancellable = cancellable($operation, $cleanup);
// Later, when you need to cancel the operation
$cancellable->cancel();
// Check if it was cancelled
if ($cancellable->isCancelled()) {
echo "Operation was cancelled.\n";
}
use function Matrix\{async, await, withErrorContext};
try {
await(withErrorContext(
async(function () {
throw new \RuntimeException('Database connection failed');
}),
'While initializing user service'
));
} catch (\Matrix\Exceptions\AsyncException $e) {
// Outputs: "While initializing user service: Database connection failed"
echo $e->getMessage() . "\n";
// Original exception is preserved as the previous exception
echo "Original error: " . $e->getPrevious()->getMessage() . "\n";
}
use function Matrix\{async, await, delay};
$result = await(delay(2.0, 'Delayed result'));
echo $result; // Outputs: Delayed result (after 2 seconds)
// Can be used in promise chains
async(fn () => 'Step 1')
->then(function ($result) {
echo "$result\n";
return delay(1.0, $result . ' -> Step 2');
})
->then(function ($result) {
echo "$result\n";
});
use function Matrix\{async, await, rateLimit};
// Create a function that's limited to 2 calls per second
$limitedFetch = rateLimit(
function ($url) {
return async(function () use ($url) {
return file_get_contents($url);
});
},
2, // Maximum 2 calls
1.0 // Per 1 second
);
// Make multiple calls
$urls = [
'https://example.com/api/1',
'https://example.com/api/2',
'https://example.com/api/3',
'https://example.com/api/4',
'https://example.com/api/5',
];
// These will automatically be rate-limited
foreach ($urls as $url) {
$limitedFetch($url)->then(function ($response) use ($url) {
echo "Fetched $url: " . strlen($response) . " bytes\n";
});
}
// Wait for all to complete
await(\Matrix\Async::delay(10)); // Give time for requests to complete