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

caciobanu/guzzle-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle
    composer require caciobanu/guzzle-bundle
    
  2. Enable the Bundle Add to config/bundles.php:
    Caciobanu\GuzzleBundle\CaciobanuGuzzleBundle::class => ['all' => true],
    
  3. Configure Clients Create config/packages/caciobanu_guzzle.yml:
    caciobanu_guzzle:
        clients:
            api:
                base_uri: 'https://api.example.com'
    
  4. First Use Case Inject the client in a controller/service:
    use Symfony\Component\HttpFoundation\Response;
    
    class ApiController extends AbstractController
    {
        public function fetchData(GuzzleHttp\Client $apiClient): Response
        {
            $response = $apiClient->get('/endpoint');
            $data = json_decode($response->getBody(), true);
            return $this->json($data);
        }
    }
    

Implementation Patterns

Dependency Injection

  • Automatic Client Registration The bundle auto-registers clients as services under caciobanu_guzzle.client.<name>. Access via:

    $client = $this->get('caciobanu_guzzle.client.api');
    

    or via autowiring:

    public function __construct(private GuzzleHttp\Client $apiClient) {}
    
  • Custom Client Classes Extend GuzzleHttp\Client for reusable logic:

    clients:
        custom:
            client_class: App\Services\CustomGuzzleClient
            base_uri: 'https://custom.example.com'
    

Configuration-Driven Workflows

  • Dynamic Client Options Use YAML to define timeouts, headers, or middleware:

    clients:
        auth_api:
            base_uri: 'https://auth.example.com'
            options:
                timeout: 10
                headers:
                    Authorization: 'Bearer {{ app.token }}'
    

    Reference Symfony parameters:

    options:
        headers:
            X-API-Key: '%env(API_KEY)%'
    
  • Middleware Integration Attach middleware via options:

    clients:
        logged:
            base_uri: 'https://api.example.com'
            options:
                middleware: ['caciobanu_guzzle.middleware.log']
    

Common Use Cases

  1. API Calls in Controllers

    $response = $apiClient->request('GET', '/users', [
        'query' => ['limit' => 10]
    ]);
    
  2. Async Requests

    $promise = $apiClient->getAsync('/data');
    $promise->then(function ($response) {
        // Handle response
    });
    
  3. Streaming Responses

    $stream = $apiClient->get('/large-file');
    file_put_contents('file.zip', $stream->getBody());
    

Gotchas and Tips

Pitfalls

  • Deprecated Symfony Version Last release in 2018 targets Symfony 3.x. For Symfony 5/6, use nelmio/cors-bundle + native Guzzle or php-http/guzzle7-adapter. Workaround: Fork the repo and update dependencies.

  • No PSR-15 Middleware Support The bundle lacks native support for PSR-15 middleware (e.g., Http\Message\Middleware). Manually attach middleware via options.middleware:

    options:
        middleware: ['GuzzleHttp\Middleware\RetryMiddleware']
    
  • Logging Overhead Enable logging: true only in dev/staging. Logging every request in production can degrade performance.

Debugging

  • Check Service Existence If $this->get('caciobanu_guzzle.client.api') fails, verify:

    1. The client is defined in caciobanu_guzzle.yml.
    2. The bundle is enabled in bundles.php.
    3. Cache is cleared (php bin/console cache:clear).
  • Validate Configuration Use php bin/console debug:config caciobanu_guzzle to inspect loaded clients.

Extension Points

  • Custom Client Factories Override the default factory by binding a service:

    # config/services.yaml
    services:
        App\Guzzle\CustomClientFactory:
            tags: ['caciobanu_guzzle.client_factory']
    
  • Event Subscribers Listen to caciobanu_guzzle.client.create to modify clients at runtime:

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Caciobanu\GuzzleBundle\Event\ClientEvent;
    
    class GuzzleSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [ClientEvent::CREATE => 'onClientCreate'];
        }
    
        public function onClientCreate(ClientEvent $event)
        {
            $event->getClient()->getConfig('timeout', 30);
        }
    }
    

Performance Tips

  • Reuse Clients Instantiate clients once (e.g., as service properties) and reuse them to avoid connection overhead.
  • Connection Pooling Configure pool options for HTTP/2:
    options:
        pool: 'http2'
    
  • Disable Verbose Mode Avoid GuzzleHttp\HandlerStack::create() in production unless necessary.

Migration Notes

  • From Guzzle 6 to 7 If upgrading Guzzle versions, replace get() with request():
    // Guzzle 6
    $client->get('/endpoint');
    
    // Guzzle 7
    $client->request('GET', '/endpoint');
    
    Update the bundle’s client_class to extend GuzzleHttp\ClientInterface if needed.
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours