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

Amp Laravel Package

amphp/amp

AMPHP (AMP) accelerates PHP concurrency with fibers, eliminating callbacks and generators. Built on PHP 8.1’s cooperative coroutines, it lets you run async tasks like sync code—ideal for I/O-bound apps. Use Amp\async() for parallel execution and Future::await() to handle results seamlessly. No event...

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require amphp/amp revolt/event-loop
    

    Ensure PHP 8.1+ is used (fibers are required).

  2. First Use Case: Replace blocking I/O with non-blocking alternatives. For example, fetch multiple URLs concurrently:

    use Amp\async;
    use Amp\Http\Client\HttpClientBuilder;
    
    $httpClient = HttpClientBuilder::buildDefault();
    $futures = [
        async(fn() => $httpClient->request('https://example.com')),
        async(fn() => $httpClient->request('https://google.com'))
    ];
    
    $results = Amp\Future\await($futures);
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Concurrent HTTP Requests: Use Amp\Future\await() to parallelize HTTP calls (e.g., with amphp/http-client):

    $futures = array_map(
        fn($url) => async(fn() => $httpClient->request($url)),
        ['url1', 'url2']
    );
    $responses = Amp\Future\await($futures);
    
  2. Database Operations: Offload blocking DB queries to fibers with amphp/mysql/amphp/postgres:

    $results = Amp\Future\await([
        async(fn() => $pdo->query('SELECT * FROM users')->fetchAll()),
        async(fn() => $pdo->query('SELECT * FROM posts')->fetchAll())
    ]);
    
  3. Event-Driven Pipelines: Chain futures with map()/catch() for transformations:

    $future = async(fn() => fetchData())
        ->map(fn($data) => processData($data))
        ->catch(fn($e) => logError($e));
    
  4. Cancellation: Pass a Cancellation token to futures for cooperative shutdown:

    $cancellation = new Amp\Cancellation;
    $future = async(fn() => longRunningTask(), $cancellation);
    $cancellation->cancel(); // Terminates the task
    

Integration Tips

  • Laravel Integration: Use Amp\async() in Laravel’s service containers or queues:

    public function handle(Job $job) {
        $result = async(fn() => $job->process())->await();
    }
    

    Note: Avoid mixing synchronous Laravel code with Amp fibers (e.g., Eloquent ORM may block).

  • Reactive Streams: Combine with amphp/byte-stream for async I/O:

    $stream = async(fn() => $socket->read());
    $data = $stream->await();
    
  • Parallel Processing: Use amphp/parallel for CPU-bound tasks:

    $results = Amp\Parallel\run(function() {
        return computeHeavyTask();
    });
    

Gotchas and Tips

Pitfalls

  1. Blocking Calls:

    • Issue: Mixing synchronous code (e.g., file_get_contents()) with fibers blocks the entire event loop.
    • Fix: Use non-blocking alternatives (amphp/byte-stream, amphp/http-client).
  2. Fiber Leaks:

    • Issue: Unawaited futures or forgotten fibers can cause memory leaks.
    • Fix: Always await() futures or use finally() to clean up:
      $future->finally(fn() => $deferred->complete());
      
  3. Cancellation Ignored:

    • Issue: Some operations (e.g., DB queries) may not respect cancellation.
    • Fix: Wrap in a cancellable context:
      $future->onCancel(fn() => $pdo->cancelQuery());
      
  4. State Sharing:

    • Issue: Fibers share memory; avoid mutable static variables.
    • Fix: Use thread-safe structures or pass data explicitly.

Debugging

  • Log Suspensions: Use Revolt\EventLoop::getSuspension()->debug() to trace fiber execution.
  • Timeouts: Add timeouts to futures to avoid deadlocks:
    $future->await(new Amp\TimeoutCancellation(1000)); // 1-second timeout
    

Extension Points

  1. Custom Futures: Extend Amp\Future for domain-specific logic:

    class CustomFuture extends Amp\Future {
        public function retry(int $attempts): self { ... }
    }
    
  2. Event Loop Hooks: Integrate with Revolt’s event loop for custom scheduling:

    Revolt\EventLoop::onTick(fn() => $this->tickHandler());
    
  3. Cancellation Strategies: Implement Amp\CancellationAwareInterface for cooperative shutdowns:

    class MyTask implements CancellationAwareInterface {
        public function onCancel(): void { ... }
    }
    

Config Quirks

  • Revolt Extensions: For high concurrency (>1024 connections), enable ext-event:
    pecl install event
    
  • Fiber Limits: PHP’s default fiber stack size (2MB) may need adjustment for deep recursion:
    Fiber::setStackSize(4 * 1024 * 1024); // 4MB stack
    

Pro Tips

  • Compose Futures: Use combinators (awaitAll, awaitAny) to build reactive pipelines:
    $results = Amp\Future\awaitAll([
        async(fn() => $db->query('SELECT * FROM users')),
        async(fn() => $cache->get('users'))
    ]);
    
  • Avoid DeferredFuture: Prefer Amp\async() unless implementing low-level async primitives.
  • Test with Amp\Loop: Use Amp\Loop::run() for isolated testing:
    Amp\Loop::run(fn() => $this->testAsyncCode());
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle