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

ddeboer/guzzle-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ddeboer/guzzle-bundle
    

    (Note: The package is archived, but still functional. Prefer modern alternatives like nelmio/api-client-bundle or php-http/guzzle-adapter for new projects.)

  2. Enable the Bundle in config/bundles.php:

    return [
        // ...
        Ddeboer\GuzzleBundle\DdeboerGuzzleBundle::class => ['all' => true],
    ];
    
  3. Basic Configuration (config/packages/ddeboer_guzzle.yaml):

    ddeboer_guzzle:
        clients:
            api:
                config:
                    base_url: 'https://api.example.com'
                    timeout: 30
    
  4. First Use Case: Inject the client in a service/controller:

    use Ddeboer\GuzzleBundle\Client\ClientInterface;
    
    class MyController extends AbstractController {
        public function __construct(private ClientInterface $client) {}
    
        public function fetchData() {
            $response = $this->client->get('api', '/endpoint');
            return $this->json($response->json());
        }
    }
    

Implementation Patterns

Common Workflows

  1. Service Integration: Create a dedicated service for API interactions:

    class ApiService {
        public function __construct(private ClientInterface $client) {}
    
        public function getUser(int $id): array {
            $response = $this->client->get('api', "/users/{$id}");
            return $response->json();
        }
    }
    
  2. Request Customization: Use middleware or request options:

    $response = $this->client->get('api', '/search', [
        'query' => ['q' => 'laravel'],
        'headers' => ['Accept' => 'application/json'],
    ]);
    
  3. Authentication: Configure auth in config/packages/ddeboer_guzzle.yaml:

    clients:
        api:
            config:
                base_url: 'https://api.example.com'
                auth: ['username', 'password']  # Basic Auth
    

    Or use middleware for token-based auth:

    $this->client->get('api', '/protected', [
        'auth' => ['token', '']
    ]);
    
  4. Response Handling: Streamline responses with custom handlers:

    $response = $this->client->get('api', '/data');
    $data = json_decode($response->getBody(), true);
    

Integration Tips

  • Dependency Injection: Prefer constructor injection for clients/services.
  • Configuration: Centralize API endpoints/config in config/packages/ddeboer_guzzle.yaml.
  • Error Handling: Wrap calls in try-catch for GuzzleException:
    try {
        $response = $this->client->get('api', '/endpoint');
    } catch (GuzzleException $e) {
        // Log or rethrow
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • The bundle is archived. Modern alternatives (e.g., nelmio/api-client-bundle) offer better support.
    • Guzzle 6+ may require adjustments (e.g., getBody()getBody()->getContents()).
  2. Configuration Overrides:

    • Client configs in yaml are merged; later definitions override earlier ones.
    • Example: Adding a client dynamically:
      $this->client->createClient('dynamic', [
          'base_url' => 'https://dynamic.example.com',
      ]);
      
  3. Middleware Conflicts:

    • Custom middleware must implement Guzzle\Common\Middleware. Example:
      use Guzzle\Common\Middleware;
      
      class AddHeaderMiddleware implements Middleware {
          public function __invoke(callable $handler) {
              return function ($request) use ($handler) {
                  $request->addHeader('X-Custom', 'Header');
                  return $handler($request);
              };
          }
      }
      
      Register in config/packages/ddeboer_guzzle.yaml:
      clients:
          api:
              middleware: ['add_header']
      
  4. Caching Responses:

    • Use Guzzle’s built-in caching middleware (not bundled by default):
      use Guzzle\Plugin\Cache\CachePlugin;
      use Guzzle\Plugin\Cache\FileCacheAdapter;
      
      $cache = new FileCacheAdapter('/path/to/cache');
      $this->client->addSubscriber(new CachePlugin($cache));
      

Debugging Tips

  • Enable Guzzle Debugging: Add to config/packages/ddeboer_guzzle.yaml:

    clients:
        api:
            config:
                debug: true
    

    (Logs requests/responses to var/log/guzzle.log.)

  • Inspect Requests: Use Guzzle\Service\Description\ServiceDescription for API discovery:

    $description = new ServiceDescription('https://api.example.com/api.xml');
    $this->client->setDescription($description);
    
  • Common Issues:

    • SSL Errors: Configure verify in client config:
      clients:
          api:
              config:
                  verify: /path/to/cert.pem
      
    • Timeouts: Set timeout in config or per-request:
      $this->client->get('api', '/slow', ['timeout' => 60]);
      

Extension Points

  1. Custom Clients: Dynamically create clients in services:

    $client = $this->client->createClient('third_party', [
        'base_url' => 'https://thirdparty.com',
    ]);
    
  2. Event Subscribers: Subscribe to Guzzle events (e.g., request.before_send):

    use Guzzle\Event\EventInterface;
    
    class MySubscriber implements SubscriberInterface {
        public function getEvents() {
            return ['request.before_send' => 'onBeforeSend'];
        }
    
        public function onBeforeSend(EventInterface $event) {
            $request = $event->getRequest();
            $request->addHeader('X-Request-ID', uniqid());
        }
    }
    

    Register in config/packages/ddeboer_guzzle.yaml:

    clients:
        api:
            subscribers: ['my_subscriber']
    
  3. PSR-7 Compatibility: Use GuzzleHttp\Psr7 for PSR-7 requests/responses if needed:

    use GuzzleHttp\Psr7\Request;
    
    $request = new Request('GET', '/endpoint');
    $response = $this->client->send($request);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui