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

bywulf/guzzle-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bywulf/guzzle-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        byWulf\CsaGuzzleBundle\CsaGuzzleBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration: Define a client in config/packages/csa_guzzle.yaml:

    csa_guzzle:
        clients:
            api:
                base_uri: 'https://api.example.com'
                timeout: 30
                options:
                    headers:
                        'Accept': 'application/json'
    
  3. First Use Case: Inject the client into a service and make a request:

    use Symfony\Component\HttpFoundation\Response;
    
    class ApiClient
    {
        public function __construct(private \GuzzleHttp\ClientInterface $apiClient) {}
    
        public function fetchData(): Response
        {
            $response = $this->apiClient->get('/endpoint');
            return new Response($response->getBody());
        }
    }
    

Where to Look First

  • Debug Toolbar: Automatically integrates with Symfony’s profiler (visible in /_profiler).
  • Configuration: Check config/packages/csa_guzzle.yaml for client-specific settings.
  • Middleware: Built-in support for logging, profiling, and caching (see Implementation Patterns).

Implementation Patterns

Common Workflows

  1. Client Configuration: Define multiple clients in config/packages/csa_guzzle.yaml:

    csa_guzzle:
        clients:
            auth:
                base_uri: 'https://auth.example.com'
                timeout: 10
                middleware:
                    - csa_guzzle.middleware.logger
                    - csa_guzzle.middleware.profiler
    
  2. Middleware Integration: Enable middleware globally or per-client:

    csa_guzzle:
        middleware:
            default:
                - csa_guzzle.middleware.cache  # Cache responses
                - csa_guzzle.middleware.mock  # For testing
    
  3. Service Injection: Use autowiring or explicit binding:

    // services.yaml
    services:
        App\Service\ApiService:
            arguments:
                $client: '@csa_guzzle.client.api'
    
  4. Async Requests: Leverage Guzzle’s promise API:

    $promise = $this->apiClient->getAsync('/data');
    $promise->then(function ($response) {
        // Handle response
    });
    

Integration Tips

  • Symfony Events: Attach middleware via event subscribers:
    use byWulf\CsaGuzzleBundle\Event\GuzzleEvent;
    
    class CustomSubscriber implements SubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                GuzzleEvent::PRE_REQUEST => 'onPreRequest',
            ];
        }
    
        public function onPreRequest(GuzzleEvent $event)
        {
            $event->getRequest()->setHeader('X-Custom', 'Header');
        }
    }
    
  • Caching: Use csa_guzzle.middleware.cache with Symfony’s cache system:
    csa_guzzle:
        clients:
            cached_api:
                middleware:
                    - csa_guzzle.middleware.cache:
                        cache_pool: 'app.cache.array'
    
  • Testing: Mock responses with csa_guzzle.middleware.mock:
    csa_guzzle:
        clients:
            test_api:
                middleware:
                    - csa_guzzle.middleware.mock:
                        responses:
                            GET:/test: '{"status":"ok"}'
    

Gotchas and Tips

Pitfalls

  1. Middleware Order: Middleware executes in the order defined. Place profiler early to capture full request/response cycles:

    middleware:
        - csa_guzzle.middleware.profiler
        - csa_guzzle.middleware.logger
    
  2. Debug Toolbar Visibility: Ensure APP_DEBUG=true in .env to see Guzzle requests in the toolbar. Profiler data may not appear in production.

  3. Deprecated Features:

    • service_descriptions (from 1.x) is not available in 2.x/3.x. Use custom middleware for API documentation.
  4. PHP 8.0+ Compatibility: While this fork supports PHP 8.0, some middleware (e.g., mock) may require adjustments for named arguments.

Debugging

  • Log Middleware: Enable logging for all requests:

    csa_guzzle:
        middleware:
            default:
                - csa_guzzle.middleware.logger:
                    log_level: debug
    

    Check var/log/dev.log for Guzzle activity.

  • Profiler Data: If the toolbar shows no Guzzle data:

    • Verify csa_guzzle.middleware.profiler is enabled.
    • Clear Symfony’s cache (php bin/console cache:clear).
  • Timeout Errors: Default timeout is 30 seconds. Adjust per-client:

    clients:
        slow_api:
            timeout: 60
    

Extension Points

  1. Custom Middleware: Create a middleware class and register it:

    use byWulf\CsaGuzzleBundle\Middleware\MiddlewareInterface;
    
    class CustomHeaderMiddleware implements MiddlewareInterface
    {
        public function __invoke(callable $handler)
        {
            return function ($request, $options) use ($handler) {
                $request = $request->withHeader('X-Custom', 'Value');
                return $handler($request, $options);
            };
        }
    }
    

    Register in services.yaml:

    services:
        app.custom_middleware:
            class: App\Middleware\CustomHeaderMiddleware
            tags:
                - { name: csa_guzzle.middleware }
    
  2. Override Default Clients: Extend or replace default clients in config/packages/overrides/csa_guzzle.yaml:

    csa_guzzle:
        clients:
            api:
                base_uri: '%env(API_URL)%'
    
  3. Event Subscribers: Extend functionality via GuzzleEvent:

    use byWulf\CsaGuzzleBundle\Event\GuzzleEvent;
    
    class RetrySubscriber implements SubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [GuzzleEvent::POST_RESPONSE => 'onPostResponse'];
        }
    
        public function onPostResponse(GuzzleEvent $event)
        {
            if ($event->getResponse()->getStatusCode() === 429) {
                $event->retry();
            }
        }
    }
    

Configuration Quirks

  • Base URI Merging: Client-specific base_uri overrides bundle defaults. Avoid duplicate paths:
    # Bad: Duplicate base_uri
    clients:
        api:
            base_uri: 'https://api.example.com/v1'
        api_v2:
            base_uri: 'https://api.example.com/v1'  # Overrides v1
    
  • Middleware Aliases: Use FQCNs for middleware (e.g., byWulf\CsaGuzzleBundle\Middleware\LoggerMiddleware) if conflicts arise.

Performance Tips

  • Connection Pooling: Reuse clients (Symfony’s container manages this by default). Avoid creating new clients per request.
  • Disable Unused Middleware: Remove unused middleware (e.g., profiler) in production to reduce overhead:
    csa_guzzle:
        middleware:
            default: []  # Disable all
    
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.
codifyo/ts-generator-bundle
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