amphp/parallel
True parallel processing for PHP with Amp: run blocking tasks in worker processes or threads without blocking the event loop and without extra extensions. Includes non-blocking concurrency tools and a worker pool API for submitting tasks and collecting results.
Start by installing the package via Composer: composer require amphp/parallel. Then identify blocking operations in your application (e.g., heavy I/O, CPU-bound tasks, or sequential database calls) that would benefit from parallelization. The first use case is typically offloading blocking I/O — like fetching many URLs — without halting your main event loop. Begin with Worker::submit() using a simple Task class implementing Task::run(), returning scalar or serializable data. Check the examples/ directory in the repo for ready-to-run samples (e.g., examples/parallel-http.php).
Task classes (e.g., EmailSenderTask, ImageResizeTask) with immutably typed constructors — avoid closures or non-serializable state to ensure proper serialize()/unserialize() across process boundaries.WorkerPool (or the global pool via workerPool()) to concurrently execute tasks across multiple processes/threads. For CPU-bound work, tune pool size to core count; for I/O-bound, larger pools may be beneficial.ContextFactory + Channel to exchange structured messages (e.g., AppMessage DTOs) between parent and child. Wrap messages in a sealed union type or enum for robust handling.LocalCache or AtomicCache) initialized inside Task::run() to persist state per worker (not across workers), ideal for caching database results or computed values across multiple tasks in the same worker.Cancellation argument in run() and periodically call $cancellation->throwIfRequested() or check $cancellation->isRequested() — especially important for long-running loops or async I/O inside tasks.Serializable, __sleep/__wakeup classes). Objects referenced in tasks must be autoloadable in both parent and worker — verify Composer’s autoload configuration (especially classmap or files) is available to worker processes.ext-parallel and ZTS PHP 8.2+, the library falls back to proc_open child processes — slower startup, but more predictable isolation. Prefer threads if using CLI SAPI with php-zts.Channel. Reopen connections inside the child context.$cancellation and handle Amp\Parallel\Worker\CancelledException where appropriate.Amp\parallel\workerPool() to inject a custom pool in tests (e.g., with a mock ContextFactory) to avoid spawning real processes during unit tests.gc_collect_cycles() or periodic worker recycling (via WorkerPool configuration or manual restarts) if necessary.How can I help you explore Laravel packages today?