spatie/async
Run PHP tasks in parallel with a simple Pool API built on PCNTL. Add closures, handle results via then/catch, and wait for completion. Ideal for speeding up batch jobs, CPU-heavy work, and IO-bound processing with multiple processes.
Strengths:
pcntl extension, enabling true parallelism (not just concurrency) for CPU-bound tasks. This is a critical fit for Laravel applications requiring high-performance batch processing, real-time data transformations, or parallelized background jobs.Illuminate\Bus\Queueable), allowing async job execution without blocking the main process. Complements Laravel’s existing queue:work system.Weaknesses:
pcntl (Linux/Unix only; Windows support is limited to WSL or custom setups). Blocker for Windows-hosted Laravel apps without WSL.try-catch or using a queue worker as a fallback).queue:work --daemon).Async::parallel() to run multiple ShouldQueue jobs in parallel.Async::run(fn() => processLargeFile())).cache() helper for shared state.strace or htop may be needed to monitor child processes.pcntl_signal_dispatch()).Async::parallel() with a fixed pool size (e.g., ->pool(4)).try-catch and log errors to a service like Sentry.pcntl is natively supported)? If Windows, is WSL or a custom setup viable?Artisan::call() loops) with parallel execution.pcntl is available (e.g., API workers, data processors).php artisan process:parallel).pcntl support.Async::parallel():
// Before (synchronous)
foreach ($files as $file) {
processFile($file);
}
// After (parallel)
Async::parallel([
fn() => processFile($files[0]),
fn() => processFile($files[1]),
]);
spatie/async for parallelism:
Async::parallel([
fn() => dispatch(new ProcessFileJob($file1)),
fn() => dispatch(new ProcessFileJob($file2)),
]);
Artisan::call() in batch scripts with Async::run().Async::parallel() for sub-tasks (e.g., parallel API calls in a job).pcntl, posix, and proctitle. Verify with:
php -m | grep -E 'pcntl|posix'
laravel/framework, spatie/laravel-queue-s3).composer.json:
"require": {
"spatie/async": "^2.0"
}
pcntl and dependencies:
pecl install pcntl
docker-php-ext-install pcntl posix # For Docker
Async calls (e.g., app/Services/AsyncProcessor.php):
use Spatie\Async\Async;
class AsyncProcessor {
public function parallelize(array $tasks, int $poolSize = 4) {
return Async::parallel($tasks)->pool($poolSize);
}
}
Async in unit tests (e.g., using Mockery or spatie/async's test helpers).pcntl enabled to validate process isolation.Async::run(fn() => processData())->then(
fn() => Log::info('Process completed', ['pid' => getmypid()])
);
htop or ps aux to monitor process counts during load testing.Async::run(), Async::parallel()), reducing maintenance overhead.getmypid()).strace -p <PID> to inspect system calls.How can I help you explore Laravel packages today?