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

csa/guzzle-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require csa/guzzle-bundle
    

    Add to config/bundles.php (Symfony 4+):

    return [
        // ...
        Csa\GuzzleBundle\CsaGuzzleBundle::class => ['all' => true],
    ];
    
  2. Configuration: Define clients in config/packages/csa_guzzle.yaml:

    csa_guzzle:
        clients:
            api:
                base_url: 'https://api.example.com'
                timeout: 30
                options:
                    headers:
                        Accept: 'application/json'
    
  3. First Use Case: Inject the client into a service (e.g., src/Service/ApiService.php):

    use Csa\GuzzleBundle\Client\ClientInterface;
    
    class ApiService {
        private $client;
    
        public function __construct(ClientInterface $client) {
            $this->client = $client;
        }
    
        public function fetchData() {
            $response = $this->client->get('endpoint');
            return json_decode($response->getBody(), true);
        }
    }
    
  4. Dependency Injection: Register the service in services.yaml:

    services:
        App\Service\ApiService:
            arguments:
                $client: '@csa_guzzle.client.api'
    

Implementation Patterns

Common Workflows

  1. Request/Response Handling: Use the client for HTTP operations with fluent methods:

    $response = $client->get('users', [
        'query' => ['limit' => 10],
        'headers' => ['Authorization' => 'Bearer token']
    ]);
    $data = json_decode($response->getBody(), true);
    
  2. Middleware Integration: Attach middleware (e.g., logging, retries) via configuration:

    csa_guzzle:
        clients:
            api:
                middleware: ['csa_guzzle.middleware.logger']
    

    Or programmatically:

    $client->getEmitter()->attach(
        new \Csa\GuzzleBundle\Middleware\LoggerMiddleware()
    );
    
  3. Dynamic Clients: Create clients dynamically in services:

    $client = $this->container->get('csa_guzzle.client_manager')->createClient('dynamic_name');
    
  4. Event Listeners: Subscribe to Guzzle events (e.g., request, response) via Symfony events:

    services:
        App\EventListener\ApiRequestListener:
            tags:
                - { name: kernel.event_listener, event: csa_guzzle.request, method: onRequest }
    
  5. Async Requests: Use promises for async operations:

    $promise = $client->getAsync('endpoint');
    $promise->then(function ($response) {
        // Handle response
    });
    

Integration Tips

  • Symfony Cache: Cache responses using Symfony’s cache system:
    csa_guzzle:
        clients:
            api:
                cache: cache.app
    
  • Monolog Integration: Log requests/responses with Monolog:
    csa_guzzle:
        clients:
            api:
                middleware: ['csa_guzzle.middleware.monolog']
    
  • API Versioning: Use environment-specific configs (e.g., config/packages/dev/csa_guzzle.yaml):
    csa_guzzle:
        clients:
            api:
                base_url: '%env(API_URL)%'
    

Gotchas and Tips

Pitfalls

  1. Deprecated Guzzle Version:

    • The bundle is archived and supports Guzzle 4/5/6 (last release: 2015).
    • Risk: Incompatibility with newer Guzzle (7+) or Symfony (5.4+). Use at your own risk or fork.
    • Workaround: Fork the repo and update dependencies manually.
  2. Configuration Overrides:

    • Config in config/packages/csa_guzzle.yaml is merged with defaults. Overrides may not work as expected.
    • Tip: Use !important in YAML or set defaults in config/packages/overrides/csa_guzzle.yaml.
  3. Middleware Conflicts:

    • Middleware like logger or monolog may not be maintained. Custom middleware might be needed.
    • Debugging: Check var/log/dev.log for Guzzle events if middleware fails silently.
  4. Service Autowiring:

    • The bundle does not support autowiring by default. Explicitly define services in services.yaml:
      services:
          Csa\GuzzleBundle\Client\ClientInterface: '@csa_guzzle.client.api'
      
  5. Deprecated Symfony Components:

    • The bundle may rely on older Symfony components (e.g., Symfony\Component\HttpFoundation). Test thoroughly in newer Symfony versions.

Debugging Tips

  1. Enable Guzzle Debug: Add debug middleware temporarily:

    $client->getEmitter()->attach(
        new \GuzzleHttp\Middleware::tap(function ($request) {
            error_log('Request: ' . $request->getUri());
        })
    );
    
  2. Check Event Dispatcher: Ensure events are subscribed correctly:

    bin/console debug:event-dispatcher | grep csa_guzzle
    
  3. Validate Config: Use Symfony’s config validator:

    bin/console config:validate csa_guzzle
    

Extension Points

  1. Custom Clients: Extend the base client class (Csa\GuzzleBundle\Client\Client) to add domain-specific methods:

    class CustomClient extends Client {
        public function customMethod() {
            return $this->post('/custom', ['json' => ['key' => 'value']]);
        }
    }
    

    Register in services.yaml:

    services:
        App\Client\CustomClient:
            parent: csa_guzzle.client
            arguments:
                - 'custom'
    
  2. Plugin System: Create plugins for reusable logic (e.g., rate limiting, auth):

    class AuthPlugin {
        public function __invoke(callable $handler) {
            return function ($request, array $options) use ($handler) {
                $request = $request->withHeader('Authorization', 'Bearer token');
                return $handler($request, $options);
            };
        }
    }
    

    Attach via config:

    csa_guzzle:
        clients:
            api:
                middleware: ['@App\Plugin\AuthPlugin']
    
  3. PSR-15 Middleware: Integrate PSR-15 middleware (e.g., http-interop/http-middleware) via Guzzle’s Middleware::map():

    $stack = \GuzzleHttp\HandlerStack::create();
    $stack->push(
        \GuzzleHttp\Middleware::mapRequest(function ($request) {
            return $request->withHeader('X-Custom', 'Header');
        })
    );
    $client = new \GuzzleHttp\Client(['handler' => $stack]);
    
  4. Testing: Mock the client in tests using Symfony’s HttpClient or GuzzleHttp\Handler\MockHandler:

    use GuzzleHttp\Handler\MockHandler;
    use GuzzleHttp\Psr7\Response;
    
    $mock = new MockHandler([new Response(200, [], '{"test": true}')]);
    $handler = \GuzzleHttp\HandlerStack::create($mock);
    $client = new \GuzzleHttp\Client(['handler' => $handler]);
    $this->container->set('csa_guzzle.client.api', $client);
    
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.
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
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