Download the PHP package jerome/matrix without Composer
On this page you can find all versions of the php package jerome/matrix. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download jerome/matrix
More information about jerome/matrix
Files in jerome/matrix
Package matrix
Short Description An unparalleled PHP asynchronous experience, offering genuine concurrency and fiber-based task management.
License MIT
Homepage https://thavarshan.com
Informations about the package matrix
Matrix
Matrix is a PHP library that brings event-driven, asynchronous programming to PHP, inspired by JavaScript's async
/await
syntax. Built on top of ReactPHP's event loop, Matrix makes it easier to write non-blocking I/O operations and manage concurrency with a simple, intuitive API.
Understanding Async in PHP
Important: PHP runs in a single-threaded environment. Matrix doesn't create true parallelism but enables event-driven, non-blocking I/O operations through ReactPHP's event loop. This means:
- ✅ Non-blocking I/O: Network requests, file operations, and timers don't block execution
- ✅ Concurrent operations: Multiple I/O operations can run simultaneously
- ❌ CPU-bound tasks: Heavy computations will still block the event loop
- ❌ True parallelism: No multiple threads or processes
Matrix shines when dealing with I/O-heavy applications like API clients, web scrapers, or microservices.
Why Choose Matrix?
Matrix simplifies ReactPHP development by providing a familiar async/await syntax while maintaining full compatibility with ReactPHP's ecosystem. It handles the complexity of promise management and event loop integration behind a clean, intuitive API.
Key Features
- JavaScript-like API: Use
async()
andawait()
for straightforward asynchronous programming - Powered by ReactPHP: Built on ReactPHP's battle-tested event loop for true non-blocking I/O
- Robust Error Handling: Catch and handle exceptions with
.catch()
ortry-catch
- Automatic Loop Management: The event loop runs automatically to handle promise resolution
- Concurrent Operations: Run multiple I/O operations simultaneously
- Rate Limiting: Control the frequency of asynchronous operations
- Promise Cancellation: Cancel pending operations when they're no longer needed
- Retry Mechanism: Automatically retry failed operations with configurable backoff strategies
- Batch Processing: Process items in batches for improved performance
- Enhanced Error Handling: Add context to errors for better debugging
Installation
Install Matrix via Composer:
Requirements
- PHP 8.0 or higher
sockets
extension enabled
ReactPHP promises and the event loop will be installed automatically via Composer.
API Overview
Core Functions
async(callable $callable): PromiseInterface
Wraps a callable into an asynchronous function that returns a promise.
await(PromiseInterface $promise, ?float $timeout = null): mixed
Awaits the resolution of a promise and returns its value. Optionally accepts a timeout in seconds.
Promise Combination
all(array $promises): PromiseInterface
Runs multiple promises concurrently and returns a promise that resolves with an array of all results.
race(array $promises): PromiseInterface
Returns a promise that resolves with the value of the first resolved promise in the array.
any(array $promises): PromiseInterface
Returns a promise that resolves when any promise resolves, or rejects when all promises reject.
Concurrency Control
map(array $items, callable $callback, int $concurrency = 0, ?callable $onProgress = null): PromiseInterface
Maps an array of items through an async function with optional concurrency control and progress tracking.
batch(array $items, callable $batchCallback, int $batchSize = 10, int $concurrency = 1): PromiseInterface
Processes items in batches rather than one at a time for improved performance.
pool(array $callables, int $concurrency = 5, ?callable $onProgress = null): PromiseInterface
Executes an array of callables with limited concurrency.
Error Handling and Control
timeout(PromiseInterface $promise, float $seconds, string $message = 'Operation timed out'): PromiseInterface
Creates a promise that times out after a specified period.
retry(callable $factory, int $maxAttempts = 3, ?callable $backoffStrategy = null): PromiseInterface
Retries a promise-returning function multiple times until success or max attempts reached.
cancellable(PromiseInterface $promise, callable $onCancel): CancellablePromise
Creates a cancellable promise with a cleanup function.
withErrorContext(PromiseInterface $promise, string $context): PromiseInterface
Enhances a promise with additional error context.
Timing and Flow Control
delay(float $seconds, mixed $value = null): PromiseInterface
Creates a promise that resolves after a specified delay.
waterfall(array $callables, mixed $initialValue = null): PromiseInterface
Executes promises in sequence, passing the result of each to the next.
rateLimit(callable $fn, int $maxCalls, float $period): callable
Creates a rate-limited version of an async function.
Examples
Running Asynchronous Tasks
Using the Await Syntax
Handling Errors
Chaining Promises
Non-blocking HTTP Requests Example
Database Operations Example (using ReactPHP MySQL)
API Integration Example with Retry
Advanced Testing
Matrix includes a comprehensive test suite to ensure reliability, including:
Unit Tests
Test individual components in isolation:
Integration Tests
Test how components work together in real-world scenarios:
Error Handling Tests
Test that errors are properly handled and propagated:
Concurrency Pattern Tests
Test various concurrency patterns:
Performance Considerations
- Event Loop: Matrix uses ReactPHP's event loop, which should be run only once in your application
- Blocking Operations: Avoid CPU-intensive tasks and blocking I/O operations (like
file_get_contents()
,sleep()
, or database queries without ReactPHP adapters) in async functions as they will block the entire event loop - Memory Management: Be mindful of memory usage when creating many promises, as they remain in memory until resolved
- Error Handling: Always handle promise rejections to prevent unhandled promise rejection warnings
- Concurrency Limits: Use the concurrency parameters in
map()
,batch()
, andpool()
to control resource usage and prevent overwhelming external services - Rate Limiting: Use
rateLimit()
when working with APIs that have rate limits to avoid being throttled
Common Pitfalls to Avoid
❌ Using Blocking Operations
✅ Use Non-blocking Alternatives
❌ CPU-Intensive Operations
✅ Break Up Heavy Operations
How It Works
Matrix provides an intuitive async/await interface on top of ReactPHP's powerful event loop system:
- Event Loop Management: The
async()
function schedules work on ReactPHP's event loop, enabling non-blocking execution of I/O operations - Promise Interface: All async operations return ReactPHP promises with
then()
andcatch()
methods for handling success and error cases - Synchronous Await: The
await()
function runs the event loop until the promise resolves, providing a synchronous-looking interface - Concurrency Control: Functions like
map()
,batch()
, andpool()
limit concurrent operations to prevent resource exhaustion - Error Handling: Custom exception classes provide detailed information about failures, timeouts, and retry attempts
Key Point: Matrix doesn't change PHP's single-threaded nature but makes it much easier to write efficient, non-blocking I/O code that can handle thousands of concurrent operations.
Testing
Run the test suite to ensure everything is working as expected:
Contributing
We welcome contributions! To get started:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Please make sure your code follows the project's coding standards and includes appropriate tests.
License
Matrix is open-source software licensed under the MIT License.
All versions of matrix with dependencies
ext-pcntl Version *
ext-posix Version *
react/event-loop Version ^1.5
react/promise Version ^3.2