Matrix is a PHP library that brings asynchronous, non-blocking functionality to PHP, inspired by JavaScript's async
/await
syntax. With Matrix, you can handle asynchronous tasks and manage concurrency using promises and a simple, intuitive API.
Matrix simplifies asynchronous programming in PHP by combining promises with ReactPHP's event loop. It supports non-blocking execution, seamless error handling, and easy integration with existing projects.
- JavaScript-like API: Use
async()
andawait()
for straightforward asynchronous programming. - Powered by ReactPHP: Ensures non-blocking execution using ReactPHP's event loop.
- Robust Error Handling: Catch and handle exceptions with
.catch()
ortry-catch
. - Automatic Loop Management: The event loop runs automatically to handle promise resolution.
Install Matrix via Composer:
composer require jerome/matrix
Ensure the following extension is enabled:
sockets
ReactPHP promises and the event loop will be installed automatically via Composer.
Wraps a callable into an asynchronous function that returns a promise.
use function async;
$func = async(fn () => 'Success');
$func->then(fn ($value) => echo $value) // Outputs: Success
->catch(fn ($e) => echo 'Error: ' . $e->getMessage());
Awaits the resolution of a promise and returns its value.
use function await;
try {
$result = await(async(fn () => 'Success'));
echo $result; // Outputs: Success
} catch (\Throwable $e) {
echo 'Error: ' . $e->getMessage();
}
$promise = async(fn () => 'Task Completed');
$promise->then(fn ($value) => echo $value) // Outputs: Task Completed
->catch(fn ($e) => echo 'Error: ' . $e->getMessage());
try {
$result = await(async(fn () => 'Finished Task'));
echo $result; // Outputs: Finished Task
} catch (\Throwable $e) {
echo 'Error: ' . $e->getMessage();
}
$promise = async(fn () => throw new \RuntimeException('Task Failed'));
$promise->then(fn ($value) => echo $value)
->catch(fn ($e) => echo 'Caught Error: ' . $e->getMessage()); // Outputs: Caught Error: Task Failed
- Event Loop Management: The
async()
function ensures the event loop runs until the promise is resolved or rejected. - Promise Interface: Promises provide
then
andcatch
methods for handling success and errors. - Synchronous Await: The
await()
function allows synchronous-style code to resolve promises.
Run the test suite to ensure everything is working as expected:
composer test
We welcome contributions! To get started, fork the repository and create a pull request with your changes.
Matrix is open-source software licensed under the MIT License.