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 Adapter Bundle Laravel Package

widop/http-adapter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require widop/http-adapter-bundle
    

    Enable the bundle in config/bundles.php:

    Widop\HttpAdapterBundle\WidopHttpAdapterBundle::class => ['all' => true],
    
  2. Configuration: Configure the default adapter in config/packages/widop_http_adapter.yaml:

    widop_http_adapter:
        adapter: guzzle  # or 'curl', 'stream', 'buzz', 'zend'
        options: ~
    
  3. First Request: Inject the Widop\HttpAdapterBundle\Client service and make a request:

    use Widop\HttpAdapterBundle\Client;
    
    class MyService
    {
        public function __construct(private Client $httpClient) {}
    
        public function fetchData()
        {
            $response = $this->httpClient->get('https://api.example.com/data');
            return json_decode($response->getBody(), true);
        }
    }
    

Key Entry Points

  • Client service: Central interface for HTTP requests.
  • Request builder: Chainable methods (get(), post(), put(), etc.) with options.
  • Response handling: Access headers, body, and status via $response->getBody(), $response->getStatusCode(), etc.

Implementation Patterns

Common Workflows

1. Basic Requests

// GET request with query params
$response = $this->httpClient->get('https://api.example.com/users', [
    'query' => ['id' => 123]
]);

// POST with JSON body
$response = $this->httpClient->post('https://api.example.com/users', [
    'json' => ['name' => 'John Doe']
]);

2. Authentication

  • Basic Auth:
    $this->httpClient->get('https://api.example.com/protected', [
        'auth' => ['username', 'password']
    ]);
    
  • Bearer Token (via headers):
    $this->httpClient->get('https://api.example.com/protected', [
        'headers' => ['Authorization' => 'Bearer token123']
    ]);
    

3. Middleware/Interceptors

Use Symfony’s HttpClient middleware or bundle-specific interceptors:

# config/packages/widop_http_adapter.yaml
widop_http_adapter:
    adapter: guzzle
    options:
        middleware:
            - Widop\HttpAdapterBundle\Middleware\LoggingMiddleware
            - Widop\HttpAdapterBundle\Middleware\RetryMiddleware

4. Adapter-Specific Features

  • cURL Options:
    widop_http_adapter:
        adapter: curl
        options:
            curl: [CURLOPT_TIMEOUT, 30]
    
  • Guzzle Stream:
    $response = $this->httpClient->get('https://large-file.example.com', [
        'stream' => true
    ]);
    

5. Dependency Injection

Bind custom clients or adapters:

// src/Service/MyCustomClient.php
class MyCustomClient extends Widop\HttpAdapterBundle\Client
{
    public function customRequest()
    {
        return $this->request('GET', 'https://custom.example.com', [
            'headers' => ['X-Custom-Header' => 'value']
        ]);
    }
}

Gotchas and Tips

Pitfalls

  1. Adapter Compatibility:

    • Not all adapters support all PHP features (e.g., stream lacks advanced auth).
    • Fix: Test with your target adapter early. Fall back to guzzle for broad compatibility.
  2. Response Handling:

    • Error Responses: Check $response->getStatusCode() before accessing $response->getBody().
      if ($response->getStatusCode() !== 200) {
          throw new \RuntimeException('API Error: ' . $response->getBody());
      }
      
    • Streaming: Forgetting stream: true may buffer large responses in memory.
  3. Configuration Overrides:

    • Bundle config in config/packages/ takes precedence over config/bundles.php defaults.
    • Tip: Use environment variables for sensitive options (e.g., auth tokens).
  4. Middleware Order:

    • Middleware runs in declaration order. Logging should be last to avoid masking errors.
    • Debugging: Temporarily remove middleware to isolate issues.

Debugging Tips

  • Enable Verbose Logging:
    widop_http_adapter:
        adapter: guzzle
        options:
            debug: true  # Logs full request/response
    
  • Check Adapter-Specific Errors:
    • cURL: Use CURLOPT_VERBOSE via config.
    • Guzzle: Enable GuzzleHttp\HandlerStack debugging.

Extension Points

  1. Custom Adapters: Implement Widop\HttpAdapter\AdapterInterface and register via DI:

    services:
        app.custom_adapter:
            class: App\Adapter\MyAdapter
            tags: ['widop.http_adapter.adapter']
    
  2. Response Transformers: Extend Widop\HttpAdapterBundle\Response to add domain-specific methods:

    class ApiResponse extends Widop\HttpAdapterBundle\Response
    {
        public function asJson(): array
        {
            return json_decode($this->getBody(), true);
        }
    }
    
  3. Event Listeners: Subscribe to widop.http_adapter.request and widop.http_adapter.response events for cross-cutting concerns (e.g., rate limiting).

Performance Tips

  • Connection Pooling: Use guzzle or buzzle for HTTP/2 and connection reuse.
  • Retry Logic: Configure via middleware:
    widop_http_adapter:
        options:
            middleware:
                - Widop\HttpAdapterBundle\Middleware\RetryMiddleware:
                    max_retries: 3
                    delay: 100
    
  • Caching: Leverage Symfony’s HttpCache or CacheAdapter for responses.

Common Config Quirks

  • Empty Options: Omit options: ~ if no adapter-specific config is needed.
  • Adapter-Specific Keys:
    • curl: Use curl: [option, value].
    • guzzle: Use guzzle: [handler, config].
  • Default Headers: Set globally:
    widop_http_adapter:
        options:
            headers:
                Accept: application/json
                User-Agent: MyApp/1.0
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor