amphp/parallel-functions
Wrap callables to run in parallel processes/threads with AMPHP. Provides helpers like parallelMap to execute CPU-heavy or blocking tasks concurrently; callable state must be serializable. Built for PHP 8.1+ with fibers-friendly concurrency.
Install the package via Composer:
composer require amphp/parallel-functions
Start with parallelMap()—the most common entry point—to run I/O-bound or CPU-heavy operations in parallel. For example, concurrently fetching multiple URLs:
use function Amp\ParallelFunctions\parallelMap;
$results = parallelMap($urls, fn($url) => file_get_contents($url));
Verify upfront:
use)proc_open)parallelMapIdeal for homogeneous tasks over collections:
$images = glob('uploads/*.jpg');
$thumbnails = parallelMap($images, fn($file) => resizeImage($file, 200, 200));
For long-running processes (e.g., queue workers), reuse a pool to avoid process thrashing:
use Amp\Parallel\Worker\DefaultPool;
$pool = new DefaultPool(4);
$results = parallelMap($tasks, $callable, $pool);
Keep logic reusable and testable outside closures:
// app/Parallel/ThumbnailGenerator.php
class ThumbnailGenerator {
public static function generate(string $file): string { /* ... */ }
}
// usage
$results = parallelMap($files, [ThumbnailGenerator::class, 'generate']);
PDO, Symfony\Component\HttpFoundation\Request) fail silently unless checked.serialize($callable) early. Laravel’s SerializableClosure helps, but still fails for:yield/generators__sleep()/__wakeup() or non-serializable propertiesuse variables$_ENV/$_SERVER['argv']).require __DIR__ . '/vendor/autoload.php'; inside the parallel callable.imagick via FPM) may be missing in CLI workers.extension_loaded('imagick') || throw new \RuntimeException('imagick required');fn() => try { return heavyTask(); } catch (\Throwable $e) { error_log($e); throw $e; }
XDEBUG_MODE=off); it causes >10x slowdown.pcntl_async_signals(true) + declare(ticks=1) if handling SIGTERM for graceful shutdowns.$pool = new DefaultPool(min(8, count($tasks))); // never let it scale to infinity
amphp/http-client) before parallelization—even inside parallelMap, blocking calls bottleneck CPU.How can I help you explore Laravel packages today?