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

Artax Laravel Package

amphp/artax

Deprecated (unmaintained) async HTTP/1.1 client for PHP built on Amp. Implements HTTP over raw TCP sockets (no ext/curl), with keep-alive pooling, redirects, gzip decoding, streaming bodies, TLS, cookies, and proxy support. Use amphp/http-client instead.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require amphp/artax
    

    (Note: This package is deprecated; prefer amphp/http-client for new projects.)

  2. Basic Request

    use Amp\Loop;
    use Artax\Client;
    use Artax\Request;
    
    Loop::run(function () {
        $client = new Client();
        $request = new Request('https://example.com');
        $response = yield $client->request($request);
        echo $response->getBody();
    });
    
  3. First Use Case: Parallel Requests

    $client = new Client();
    $requests = [
        new Request('https://api.example.com/users'),
        new Request('https://api.example.com/posts'),
    ];
    
    $responses = yield $client->requestAll($requests);
    foreach ($responses as $response) {
        echo $response->getBody();
    }
    

Where to Look First

  • Examples Directory – Practical use cases (e.g., streaming, redirects, forms).
  • Docs – API reference and conceptual guides.
  • Changelog – Critical fixes (e.g., 3.0.8 for null pointer access, 3.0.12 for timeout leaks).

Implementation Patterns

Core Workflows

  1. Asynchronous Requests Use yield with Client::request() to avoid blocking. Ideal for I/O-bound tasks (e.g., scraping, APIs).

    $response = yield $client->request(new Request('https://example.com'));
    
  2. Connection Pooling Artax reuses HTTP/1.1 keep-alive connections by default. Configure timeouts per request:

    $request = new Request('https://example.com');
    $request->setTimeout(5.0); // 5-second timeout
    
  3. Streaming Responses Handle large responses without loading them entirely into memory:

    $response = yield $client->request(new Request('https://example.com/large-file'));
    $body = yield $response->getBody();
    while (!$body->isFinished()) {
        $chunk = yield $body->read();
        // Process chunk
    }
    
  4. Redirect Handling Enable/disable redirects via Request::setFollowRedirects() (default: true).

    $request->setFollowRedirects(false); // Disable for custom logic
    
  5. Form Submissions Use Request::setFormParams() for multipart/form-data:

    $request->setFormParams(['key' => 'value']);
    $request->setMethod('POST');
    

Integration Tips

  • Laravel Integration: Wrap Artax in a Laravel service provider to expose a singleton client:

    // app/Providers/ArtaxServiceProvider.php
    public function register()
    {
        $this->app->singleton(Client::class, function () {
            return new Client();
        });
    }
    

    Use in controllers:

    use Amp\Loop;
    use Artax\Client;
    
    public function fetchData()
    {
        $client = app(Client::class);
        $response = Loop::run(function () use ($client) {
            return $client->request(new Request('https://api.example.com/data'));
        });
        return $response->getBody();
    }
    
  • Error Handling: Catch Artax\Exception\SocketException, Artax\Exception\TimeoutException, etc.:

    try {
        $response = yield $client->request($request);
    } catch (Artax\Exception\ExceptionInterface $e) {
        Log::error("Request failed: " . $e->getMessage());
    }
    
  • Testing: Use Artax\MockHttpClient for unit tests (if available) or mock the Client interface.


Gotchas and Tips

Pitfalls

  1. Deprecation Warning: Artax is no longer maintained. Migrate to amphp/http-client for long-term projects.

    • Workaround: Use this package only for legacy systems or short-term needs.
  2. Memory Leaks:

    • Issue: Unconsumed response bodies or improper cleanup can leak resources (e.g., 3.0.7 fix for GC issues).
    • Fix: Always consume bodies explicitly:
      $body = yield $response->getBody();
      yield $body->read(); // Consume fully or stream
      
  3. Timeouts:

    • Issue: Timeouts may not apply to TLS handshakes (fixed in 3.0.12).
    • Tip: Set timeouts per request:
      $request->setTimeout(10.0); // Connection + transfer timeout
      
  4. Redirects with Host Changes:

    • Issue: Redirects to different hosts (e.g., httphttps) may fail silently (fixed in 3.0.0).
    • Tip: Verify Request::setFollowRedirects(true) and check logs for host mismatches.
  5. Cookie Handling:

    • Issue: IDN (Internationalized Domain Names) support may break cookie parsing (fixed in 3.0.2).
    • Tip: Use ASCII-compatible domains or upgrade to amphp/http-client.
  6. Chunked Transfers:

    • Issue: Responses without Content-Length or Transfer-Encoding: chunked may hang (fixed in 3.0.11).
    • Tip: Ensure servers send proper headers or stream responses manually.

Debugging Tips

  1. Enable Verbose Logging:

    $client = new Client();
    $client->setLogger(new \Monolog\Logger('artax', [
        new \Monolog\Handler\StreamHandler('php://stderr', \Monolog\Logger::DEBUG),
    ]));
    
  2. Inspect Headers:

    $headers = $response->getHeaders();
    print_r($headers->toArray());
    
  3. Check for Aborted Requests:

    • Use yield $response->getBody() to detect incomplete responses (e.g., server disconnects).

Extension Points

  1. Custom Middleware: Intercept requests/responses via Client::addMiddleware():

    $client->addMiddleware(function (Request $request, callable $next) {
        $request->setHeader('X-Custom-Header', 'value');
        return $next($request);
    });
    
  2. Proxy Support: Configure proxies via Client::setProxy():

    $client->setProxy('http://proxy.example.com:8080');
    
  3. TLS Customization: Override TLS settings (e.g., for self-signed certs):

    $client->setTlsContext(function (\GuzzleHttp\Ring\Client\TlsContext $context) {
        $context->setCaFile('/path/to/cert.pem');
    });
    

Performance Quirks

  • Lazy Parsing: TLS certificates are parsed lazily (since 3.0.9) to reduce memory usage.
  • Connection Reuse: Keep-alive connections improve throughput but may require tuning timeouts.
  • Body Size Limits: Enforced by default (since 3.0.1) to prevent zip bombs. Adjust via Request::setBodySizeLimit().
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.
phpshko/laravel-livewire-depdrop
larasell-dev/larasell
calliostro/spotify-bundle
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