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

Http Client Laravel Package

amphp/http-client

Asynchronous HTTP client for PHP built on Revolt with fibers and concurrency. Supports HTTP/1 & HTTP/2, concurrent requests, connection pooling, redirects, gzip/deflate decoding, streaming bodies, TLS by default, cookies/sessions, proxies, and custom methods—no ext/curl dependency.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven & Async-First: Aligns perfectly with modern PHP architectures leveraging AMPHP’s fiber-based concurrency model, enabling non-blocking I/O for high-throughput services (e.g., APIs, microservices, or real-time systems).
  • Protocol Agnostic: Supports HTTP/1.1 and HTTP/2, making it versatile for legacy and modern web services. HTTP/2 multiplexing reduces latency for concurrent requests.
  • PSR-7 Compatibility: While mutable (unlike PSR-7), it provides similar interfaces (Request, Response), easing migration for teams familiar with PSR standards.
  • Interceptable Pipeline: The interceptor pattern (e.g., FollowRedirects, RetryRequests) enables middleware-like customization, similar to frameworks like Laravel’s middleware or Symfony’s HTTP client interceptors.

Integration Feasibility

  • No ext/curl Dependency: Eliminates conflicts with existing curl-based clients (e.g., Guzzle) and reduces attack surface.
  • Laravel Compatibility:
    • Can integrate with Laravel’s HTTP client facade (Illuminate\Support\Facades\Http) via custom macros or adapters.
    • Works alongside Laravel Echo/Pusher (if using async WebSocket endpoints).
    • Queue Workers: Ideal for async task processing (e.g., background jobs fetching external APIs).
  • Database/ORM Synergy: Streams large responses efficiently, reducing memory pressure for bulk data imports (e.g., CSV/JSON APIs).

Technical Risk

  • Fiber Adoption Barrier:
    • Requires PHP 8.1+ with AMPHP’s fiber support (not enabled by default). May need runtime configuration (phar.ini or php.ini).
    • Mitigation: Use Amp\run() or Amp\Loop explicitly in Laravel’s service providers or console commands.
  • Stateful Connections:
    • HTTP/2 connection pooling improves performance but may complicate debugging (e.g., shared state across requests).
    • Mitigation: Monitor connection leaks with HttpClientBuilder::setConnectionLimit().
  • PSR-7 Deviations:
    • Mutable Request/Response objects may conflict with immutable PSR-7 expectations in some libraries.
    • Mitigation: Wrap objects in immutable adapters if needed.
  • TLS Overhead:
    • Secure-by-default TLS adds latency. For internal services, consider disabling verification via HttpClientBuilder::setTlsContext() (security risk).

Key Questions

  1. Concurrency Model:
    • How will this interact with Laravel’s queue workers or synchronous HTTP clients (e.g., Guzzle)? Will we need a hybrid approach?
  2. Error Handling:
    • How to surface async errors (e.g., timeouts, connection drops) to Laravel’s exception handler?
  3. Testing:
    • How to mock HttpClient in unit tests (e.g., for API service classes)?
  4. Performance Baseline:
    • Benchmark against Guzzle (with async support) or ReactPHP for Laravel’s specific use cases (e.g., API polling).
  5. Dependency Management:
    • Will amphp/http-client conflict with existing AMPHP packages (e.g., amphp/artax) or Laravel’s symfony/http-client?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • HTTP Client: Replace Guzzle in Http facade or use alongside it for async routes.
    • Queues: Ideal for async API calls in jobs (e.g., fetchUserDataFromThirdParty).
    • Livewire/Inertia: Async data loading for SPAs (e.g., polling external APIs).
    • Laravel Horizon: Monitor async HTTP tasks in queue workers.
  • Infrastructure:
    • Docker/Kubernetes: Lightweight, no curl dependencies reduce image size.
    • Serverless: Works with PHP-FPM + fibers (e.g., AWS Lambda, Bref).

Migration Path

  1. Pilot Phase:
    • Replace non-critical Guzzle calls in Laravel’s App\Services layer with amphp/http-client.
    • Example: Async API polling for analytics or notifications.
  2. Facade Integration:
    • Extend Laravel’s Http facade to support async clients:
      // app/Providers/AppServiceProvider.php
      use Amp\Http\Client\HttpClientBuilder;
      
      public function boot()
      {
          \Illuminate\Support\Facades\Http::macro('async', function ($uri, array $options = []) {
              $client = HttpClientBuilder::buildDefault();
              return $client->request(new \Amp\Http\Client\Request($uri));
          });
      }
      
  3. Queue Workers:
    • Convert synchronous API calls in jobs to async:
      use Amp\Loop;
      
      public function handle()
      {
          Loop::run(function () {
              $client = HttpClientBuilder::buildDefault();
              $response = $client->request(new Request('https://api.example.com/data'));
              // Process response...
          });
      }
      
  4. Middleware/Interceptors:
    • Migrate Laravel middleware to AMPHP interceptors (e.g., auth headers, retries).

Compatibility

  • Laravel Packages:
    • Laravel Scout: Async index updates via HTTP.
    • Spatie API Resources: Stream responses for large payloads.
    • Cashier/Payments: Async webhook processing.
  • Third-Party APIs:
    • Test with rate-limited APIs (e.g., Stripe, Twilio) to validate concurrency handling.
    • Verify cookie/session support for auth-heavy services.

Sequencing

  1. Phase 1: Async background jobs (low-risk).
  2. Phase 2: Async route handlers (e.g., /webhooks).
  3. Phase 3: Replace synchronous HTTP clients in services.
  4. Phase 4: Optimize connection pooling (HTTP/2) for high-traffic endpoints.

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor AMPHP’s release cycle (quarterly major versions). Test upgrades for BC breaks.
    • Tooling: Use composer why-not to audit dependency conflicts.
  • Debugging:
    • Logging: Leverage LogHttpArchive for HAR files in staging.
    • Tracing: Integrate with Laravel Telescope or OpenTelemetry for request tracking.
  • Documentation:
    • Add internal docs for fiber usage (e.g., "Always wrap async calls in Amp\Loop").

Support

  • Error Handling:
    • Customize RetryRequests interceptor for Laravel’s exception handling:
      $client->intercept(new RetryRequests(
          new ExponentialBackoff(100, 3),
          new AllowedMethods(['GET', 'POST'])
      ));
      
    • Surface async errors via Laravel’s App\Exceptions\Handler.
  • Vendor Lock-in:
    • Mitigation: Abstract HttpClient behind an interface for easier swaps (e.g., fallback to Guzzle).

Scaling

  • Horizontal Scaling:
    • Stateless design (connection pooling per process) works well with Laravel Forge/Vagrant or Kubernetes.
    • Warning: HTTP/2 connection limits may require tuning (setConnectionLimit()).
  • Vertical Scaling:
    • Fiber-based concurrency reduces server load for high-QPS endpoints (e.g., 1000+ requests/sec).
  • Resource Usage:
    • Memory: Stream responses for large payloads (e.g., file downloads).
    • CPU: TLS overhead may increase CPU usage; consider nghttp2 FFI for HTTP/2.

Failure Modes

Failure Scenario Impact Mitigation
Fiber deadlocks Hangs async requests Use Amp\delay() for cooperative yielding.
Connection pool exhaustion Timeouts under load Monitor with HttpClient::getConnectionCount().
TLS handshake failures Broken HTTPS requests Validate setTlsContext() in staging.
Redirect loops Infinite retries Set followRedirects(5) or custom interceptor.
Large response buffering OOM errors Stream responses with Payload::read().

Ramp-Up

  • Team Training:
    • Async Mindset: Train devs on fiber vs. thread differences (e.g., no shared state).
    • Debugging: Use Amp\Loop::run() in Tinker for interactive testing.
  • CI/CD:
    • Add fiber support to Laravel’s Docker/Pipeline configs:
      RUN docker-php-ext-install amphp
      
    • Test async code paths in PHPUnit with Amp\Loop::run() wrappers.
  • Rollback Plan:
    • Maintain Guzzle as a fallback for critical paths during migration.
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope