Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fork Laravel Package

spatie/fork

Run PHP code concurrently using lightweight process forking. Define multiple closures and execute them in parallel, collecting results in order. Requires PHP 8 with pcntl (CLI only) and posix extensions on Unix-like systems.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/fork
    

    No additional configuration is required—just require the package in your project.

  2. First Use Case: Run a simple concurrent task:

    use Spatie\Fork\Fork;
    
    $fork = Fork::create(function () {
        // Long-running or blocking task (e.g., API calls, file processing)
        sleep(2);
        echo "Forked task completed\n";
    });
    
    $fork->run(); // Runs in a separate process
    echo "Main process continues\n";
    
  3. Where to Look First:

    • Documentation (if available; otherwise, check the GitHub README).
    • Spatie\Fork\Fork class for core functionality.
    • Spatie\Fork\Exceptions for error handling.

Implementation Patterns

Usage Patterns

  1. Fire-and-Forget Tasks: Use for non-critical, long-running operations (e.g., sending emails, generating reports).

    Fork::create(function () {
        Mail::to('user@example.com')->send(new WelcomeEmail());
    })->run();
    
  2. Parallel Processing: Execute multiple tasks concurrently:

    $forks = collect(range(1, 5))->map(fn ($i) =>
        Fork::create(fn () => processItem($i))->run()
    );
    
  3. Resource-Intensive Workloads: Offload CPU-heavy tasks (e.g., image resizing, data transformations):

    Fork::create(function () {
        $image = Image::make('large.jpg')->resize(800, 600)->save('small.jpg');
    })->run();
    
  4. Integration with Queues: Use alongside Laravel queues for hybrid concurrency:

    Fork::create(function () {
        dispatch(new ProcessDataJob());
    })->run();
    

Workflows

  • Error Handling: Wrap Fork execution in try-catch to handle failures gracefully:

    try {
        $fork->run();
    } catch (\Spatie\Fork\Exception $e) {
        Log::error("Fork failed: " . $e->getMessage());
    }
    
  • Synchronization: Use Fork::wait() to block until all forks complete (if needed):

    $forks = collect([...])->map(...);
    foreach ($forks as $fork) $fork->run();
    Fork::wait(); // Blocks until all forks finish
    
  • Environment Awareness: Avoid forking in environments where it’s unsafe (e.g., shared hosting). Check app()->runningInConsole() or environment variables.

Integration Tips

  • Logging: Redirect fork output to Laravel logs:

    Fork::create(function () {
        Log::info("Task running in fork");
    })->run();
    
  • Configuration: Adjust PHP settings (e.g., max_execution_time, memory_limit) if forks fail due to resource constraints.

  • Testing: Mock Fork in tests using partialMock:

    $mock = $this->partialMock(Fork::class, ['run']);
    $mock->shouldReceive('run')->once();
    

Gotchas and Tips

Pitfalls

  1. State Sharing:

    • Forks run in separate processes; shared memory (e.g., Laravel session, cache) is not synchronized.
    • Avoid relying on global state or static variables across forks.
  2. Resource Limits:

    • Forks inherit PHP’s memory_limit and max_execution_time. Exceeding these may silently fail.
    • Fix: Increase limits or use ini_set() in the forked closure (if allowed by your environment):
      Fork::create(function () {
          ini_set('memory_limit', '512M');
          // Task here
      })->run();
      
  3. Blocking Operations:

    • Forks cannot interact with the main process’s request lifecycle (e.g., middleware, HTTP responses).
    • Workaround: Use queues or events for cross-process communication.
  4. Windows Compatibility:

    • Forking is not supported on Windows (uses pcntl_fork, which is Unix-only).
    • Solution: Use a Unix-based environment (e.g., Docker, CI/CD) or fall back to queues.
  5. Signal Handling:

    • Forks may not handle PHP signals (e.g., SIGTERM) gracefully.
    • Tip: Implement cleanup in the forked closure (e.g., close files, release locks).

Debugging

  • Output: Redirect STDOUT/STDERR to a file for debugging:

    Fork::create(function () {
        file_put_contents('fork.log', print_r(['debug' => true], true), FILE_APPEND);
    })->run();
    
  • Process Inspection: Use ps aux | grep php (Linux/macOS) to check for zombie forks if tasks hang.

  • Timeouts: Set a timeout for the forked process:

    $fork = Fork::create(fn () => sleep(10));
    $fork->run();
    if (!$fork->isFinished()) {
        $fork->terminate(); // Force-kill if needed
    }
    

Tips

  1. Idempotency: Design forked tasks to be idempotent (retry-safe) since failures may go unnoticed.

  2. Environment Checks: Disable forking in non-Unix environments:

    if (!Fork::isSupported()) {
        Log::warning("Forking not supported; falling back to synchronous execution.");
        // Fallback logic
    }
    
  3. Performance Tuning:

    • Limit concurrent forks to avoid overwhelming the system:
      $semaphore = new \Slim\Semaphore(5); // Max 5 concurrent forks
      $semaphore->acquire();
      Fork::create(fn () => $semaphore->release())->run();
      
  4. Extension Points:

    • Override Spatie\Fork\Fork to add pre/post-fork hooks:
      class CustomFork extends Fork {
          public function run() {
              $this->logStart();
              parent::run();
              $this->logEnd();
          }
      }
      
  5. Alternatives:

    • For Laravel, consider laravel-horizon (for queues) or reactphp (for async I/O) if forking is too restrictive.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport