mehr-als-nix/parallel
Lightweight PHP library to run multiple tasks in parallel using a Manager/Worker model. Uses pcntl on *NIX to fork processes (auto-detects CPU count), with graceful fallback to serial execution when requirements aren’t met. Captures results and errors per worker.
Install via Composer: composer require mehr-als-nix/parallel. Then, for CLI jobs (e.g., Artisan commands, pipelines), instantiate a Manager, add Worker instances wrapping your callback logic, call execute(), and read results via getResult() on each worker after completion. Start with the example.php in the repo—copy it into your project and adjust paths/callbacks. Critical first check: Confirm you're running CLI (php -r 'echo SAPI_NAME;' → cli) and that pcntl is enabled (php -m | grep pcntl). If not, tasks run silently in serial with a warning.
Worker. Group them into a Manager and execute in parallel to reduce total runtime (e.g., fetching 100 remote endpoints in 2s instead of 10s).$manager->setMaxProcesses($count) to cap workers (e.g., avoid overwhelming an external API). Useful when auto-detection overcommits resources or in shared dev environments.try { ... } catch (\Throwable $e) { throw new \RuntimeException('...', 123); }—exceptions are caught per-worker and stored. After execute(), iterate workers, check getReturnCode() and getError(), and decide (e.g., retry, log, skip).foreach ($manager as $worker) (both interface styles preserve insertion order), but remember: results may be ready out-of-order. Sort if sequence matters.pcntl? Parallelism disabled—silently falls back to serial execution with E_USER_NOTICE. Many PHP-FPM/Docker/cloud environments (e.g., Laravel Vapor, Forge) disable pcntl by default—test in production-like envs early.pcntl exists, running via web server (e.g., Nginx → PHP-FPM) triggers degraded mode. Always run via CLI (php artisan my:command).$obj->prop = 'x' inside a worker does not affect the parent. Treat workers as black-box processes—use return values and serialization for data flow.getError() and avoid blocking callbacks.pcntl_fork()-like var_dump(['pid' => getmypid(), 'worker' => $i]) inside workers to verify forking. Compare PIDs to confirm true parallelism (not sequential).How can I help you explore Laravel packages today?