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

Guzzle Bundle Laravel Package

eightpoints/guzzle-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require eightpoints/guzzle-bundle

Symfony Flex automatically registers the bundle. For non-Flex projects, add to config/bundles.php:

EightPoints\Bundle\GuzzleBundle\EightPointsGuzzleBundle::class => ['all' => true],
  1. Configure a Client: Create config/packages/eight_points_guzzle.yaml:

    eight_points_guzzle:
        clients:
            api:
                base_url: 'https://api.example.com'
                options:
                    headers:
                        Accept: 'application/json'
    
  2. First Use Case: Inject the client into a service/controller:

    use Psr\Http\Client\ClientInterface;
    
    class MyService {
        public function __construct(private ClientInterface $apiClient) {}
    
        public function fetchData() {
            $response = $this->apiClient->request('GET', '/endpoint');
            return json_decode($response->getBody(), true);
        }
    }
    

Implementation Patterns

1. Client Configuration

  • Multi-Client Setup: Define multiple clients in eight_points_guzzle.yaml for different APIs (e.g., payment, crm).
  • Lazy Loading: Use lazy: true for clients initialized on-demand (reduces startup overhead):
    clients:
        payment:
            lazy: true
    
  • Dynamic Base URLs: Use environment variables or Symfony parameters for flexibility:
    base_url: '%env(API_URL)%'
    

2. Autowiring

  • Type-Hinting: Autowire clients by type (ClientInterface) or alias:
    public function __construct(private ClientInterface $apiClient) {}
    
  • Custom Aliases: Create service aliases for cleaner DI:
    services:
        App\Service\PaymentService:
            arguments:
                $client: '@eight_points_guzzle.client.payment'
    

3. Request Workflows

  • Reusable Requests: Use GuzzleHttp\Psr7\Request for pre-built requests:
    $request = new Request('POST', '/orders', [], json_encode($data));
    $response = $this->apiClient->send($request);
    
  • Async Requests: Leverage Guzzle’s promises for parallel calls:
    $promises = [
        $this->apiClient->requestAsync('GET', '/orders'),
        $this->apiClient->requestAsync('GET', '/users'),
    ];
    $responses = \GuzzleHttp\Promise\Utils::settle($promises)->wait();
    

4. Plugins Integration

  • OAuth2 Example: Add to Kernel.php:
    yield new EightPoints\Bundle\GuzzleBundle\EightPointsGuzzleBundle([
        new \Gregurco\Bundle\GuzzleBundleOAuth2Plugin\GuzzleBundleOAuth2Plugin(),
    ]);
    
  • Retry Plugin: Configure in YAML:
    clients:
        api:
            plugin:
                retry:
                    max_retries: 3
                    delay: 100
    

5. Event-Driven Extensions

  • Pre/Post Hooks: Listen to events for request/response modification:
    services:
        App\EventListener\GuzzleListener:
            tags:
                - { name: 'kernel.event_listener', event: 'eight_points_guzzle.pre_transaction.api', method: 'onPreRequest' }
    
    public function onPreRequest(PreTransactionEvent $event) {
        $event->getRequest()->setHeader('X-Custom-Header', 'value');
    }
    

Gotchas and Tips

Configuration Pitfalls

  1. Curl Options:

    • Convert CURLOPT_* to lowercase (e.g., sslversion instead of CURLOPT_SSLVERSION).
    • Example:
      options:
          curl:
              sslversion: 6  # TLS 1.2
      
    • Debugging: Use guzzlehttp/guzzle:^7.0 with --verbose flag to inspect raw requests.
  2. Lazy Loading:

    • Lazy clients (lazy: true) are initialized on first use. Avoid circular dependencies in DI.
  3. Plugin Conflicts:

    • Ensure plugins are compatible with Guzzle 7.x (e.g., gregurco/GuzzleBundleOAuth2Plugin may need updates).
    • Tip: Test plugins in isolation before bundling.

Debugging

  1. Symfony Profiler:

    • Enables HTTP request/response inspection in the Guzzle tab.
    • Dark Mode: Supported in recent versions (v8.4.0+).
  2. Logging:

    • Default format: [{datetime}] eight_points_guzzle.{level}: {method} {uri} {code}.
    • Customize: Override eight_points_guzzle.symfony_log_formatter.pattern in config:
      eight_points_guzzle:
          symfony_log_formatter:
              pattern: '[Guzzle] {method} {uri} ({code})'
      
  3. Slow Responses:

    • Set slow_response_time (ms) to log slow requests:
      eight_points_guzzle:
          slow_response_time: 1000  # Log responses >1s
      

Performance Tips

  1. Connection Pooling:

    • Reuse clients (e.g., singleton services) to leverage HTTP keep-alive.
    • Avoid: Creating new clients per request.
  2. Caching:

    • Use gregurco/GuzzleBundleCachePlugin for response caching:
      clients:
          api:
              plugin:
                  cache:
                      adapter: 'cache.app'
                      ttl: 300
      
  3. Error Handling:

    • Disable exception throwing for 4xx/5xx responses (configurable):
      clients:
          api:
              options:
                  exceptions: false
      
    • Tip: Use try-catch with GuzzleException for granular control.

Extension Points

  1. Custom Client Class:

    • Override the default GuzzleHttp\Client by configuring:
      eight_points_guzzle:
          client_class: 'App\Service\CustomGuzzleClient'
      
    • Use Case: Add middleware or logging layers.
  2. Environment Variables:

    • Dynamically set options via %env%:
      options:
          auth:
              - '%env(API_USERNAME)%'
              - '%env(API_PASSWORD)%'
      
  3. Single-File Plugins:

    • Create lightweight plugins without full bundles (see docs).
    • Example: Add a header middleware:
      // src/Plugin/CustomHeaderPlugin.php
      use EightPoints\Bundle\GuzzleBundle\Plugin\PluginInterface;
      
      class CustomHeaderPlugin implements PluginInterface {
          public function apply(ClientBuilder $builder) {
              $builder->getHandlerStack()->push(
                  Middleware::tap(function ($request) {
                      $request = $request->withHeader('X-Custom', 'value');
                      return $request;
                  })
              );
          }
      }
      
    • Register in Kernel.php:
      yield new EightPoints\Bundle\GuzzleBundle\EightPointsGuzzleBundle([
          new CustomHeaderPlugin(),
      ]);
      

Common Issues

  1. SSL Errors:

    • Disable verification (temporarily for testing):
      options:
          curl:
              verify: false
      
    • Production: Use proper certificates or configure CA bundles.
  2. Circular Dependencies:

    • Avoid injecting services that depend on Guzzle clients into the client’s constructor.
  3. Plugin Loading Order:

    • Plugins are applied in registration order. Test critical plugins first.
  4. Symfony 7+ Deprecations:

    • Use Throwable instead of Exception in event listeners (v8.5.0+).
    • Update to latest version for compatibility.

---
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.
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views