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

dormilich/http-client

Lightweight PHP HTTP client wrapper focused on simple requests and responses, with a clean API for common HTTP methods and header/body handling. Useful as a minimal dependency for sending HTTP calls without a full-featured framework.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dormilich/http-client
    

    Add the package to your config/app.php providers (if not auto-discovered):

    Dormilich\HttpClient\Providers\HttpClientServiceProvider::class,
    
  2. Basic Usage Register the HTTP client in your service container (e.g., AppServiceProvider):

    use Dormilich\HttpClient\Client;
    use Psr\Http\Message\RequestFactoryInterface;
    use Psr\Http\Message\StreamFactoryInterface;
    
    public function register()
    {
        $this->app->singleton(Client::class, function ($app) {
            return new Client(
                $app->make(RequestFactoryInterface::class),
                $app->make(StreamFactoryInterface::class),
                $app->make(\Psr\Http\Client\ClientInterface::class)
            );
        });
    }
    
  3. First Request Inject Client into a controller or service and make a request:

    use Dormilich\HttpClient\Client;
    
    public function fetchData(Client $client)
    {
        $response = $client->request('GET', 'https://api.example.com/data');
        $body = $response->getBody()->getContents();
        return json_decode($body, true);
    }
    
  4. Key Classes to Explore

    • Client: Main facade for HTTP requests.
    • Response: Handles response parsing and data extraction.
    • Request: Builds and configures requests.

Implementation Patterns

Common Workflows

1. Structured Requests with Middleware

Chain middleware for request/response transformations:

$client->withMiddleware([
    new \Dormilich\HttpClient\Middleware\AddHeader('X-Custom-Header', 'value'),
    new \Dormilich\HttpClient\Middleware\JsonEncode(),
])->request('POST', 'https://api.example.com', ['key' => 'value']);

2. Reusable Request Builders

Create a service to encapsulate request logic:

class ApiService {
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function getUser($id)
    {
        return $this->client->request('GET', "/users/{$id}");
    }
}

3. Handling Responses

Parse responses with helper methods:

$response = $client->request('GET', 'https://api.example.com/data');
$data = $response->json(); // Auto-decodes JSON
$status = $response->getStatusCode();

4. Error Handling

Use exceptions or custom logic:

try {
    $response = $client->request('GET', 'https://api.example.com/nonexistent');
} catch (\Psr\Http\Client\NetworkExceptionInterface $e) {
    // Handle network errors
} catch (\Dormilich\HttpClient\Exception\RequestException $e) {
    // Handle HTTP errors (4xx, 5xx)
}

5. Testing

Mock the ClientInterface for unit tests:

$mockClient = $this->createMock(\Psr\Http\Client\ClientInterface::class);
$this->app->instance(\Psr\Http\Client\ClientInterface::class, $mockClient);

Integration Tips

Laravel-Specific

  • Service Container: Leverage Laravel’s DI to inject Client anywhere.
  • Config: Extend the package’s config (if any) via config/http-client.php.
  • Events: Listen for request/response events if the package supports them (not documented here, but check for events() in the ServiceProvider).

PSR-18 Compliance

  • The package wraps a PSR-18 client (e.g., GuzzleHttp\Client, Symfony\HttpClient). Ensure your PSR-18 client is properly bound in the container.

Retries and Timeouts

  • Configure retries/timeout via the underlying PSR-18 client (e.g., Guzzle’s delay, timeout options).

Gotchas and Tips

Pitfalls

  1. No Built-in Retries

    • The package itself doesn’t handle retries. Use middleware or configure the underlying client (e.g., Guzzle’s retry middleware).
  2. Response Parsing Assumptions

    • Methods like json() assume the response is JSON. Validate content-type or handle exceptions:
      if ($response->getHeaderLine('Content-Type') !== 'application/json') {
          throw new \RuntimeException('Unexpected content type');
      }
      
  3. Stream Handling

    • Large responses may consume memory. Stream responses for file downloads:
      $response = $client->request('GET', 'https://example.com/large-file');
      file_put_contents('file.pdf', $response->getBody());
      
  4. Middleware Order

    • Middleware runs in the order they’re added. Place authentication middleware first:
      $client->withMiddleware([
          new AuthMiddleware(),
          new LoggingMiddleware(),
      ]);
      

Debugging

  • Enable Debugging for Underlying Client If using Guzzle, add:

    $client->withMiddleware(new \GuzzleHttp\Middleware::tap(function ($request) {
        \Log::debug('Request:', [$request->getUri(), $request->getHeaders(), $request->getBody()]);
    }));
    
  • Check Response Headers Use getHeaders() to inspect raw headers for clues:

    $headers = $response->getHeaders();
    

Extension Points

  1. Custom Middleware Implement \Dormilich\HttpClient\Middleware\RequestMiddlewareInterface or \ResponseMiddlewareInterface:

    class CustomMiddleware implements RequestMiddlewareInterface {
        public function __invoke($request, callable $next) {
            $request = $request->withHeader('X-Custom', 'value');
            return $next($request);
        }
    }
    
  2. Response Decorators Extend \Dormilich\HttpClient\Response to add custom parsing methods.

  3. Underlying Client Swap Replace the PSR-18 client binding to use a different implementation (e.g., Symfony’s HttpClient).

Config Quirks

  • No Default Config The package is lightweight and doesn’t ship with config files. All settings are passed via constructor or middleware.

  • PSR-18 Client Dependencies Ensure your PSR-18 client (e.g., Guzzle) is properly configured for timeouts, proxies, etc., outside this package.

Performance Tips

  • Reuse Connections The package is thin; performance depends on the underlying PSR-18 client. Configure connection pooling (e.g., Guzzle’s http_defaults).
  • Avoid Blocking Use async features of the underlying client if available (e.g., Guzzle’s transferStats).
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky