Installation:
composer require csa/guzzle-bundle
Add to config/bundles.php (Symfony 4+):
return [
// ...
Csa\GuzzleBundle\CsaGuzzleBundle::class => ['all' => true],
];
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'
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);
}
}
Dependency Injection:
Register the service in services.yaml:
services:
App\Service\ApiService:
arguments:
$client: '@csa_guzzle.client.api'
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);
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()
);
Dynamic Clients: Create clients dynamically in services:
$client = $this->container->get('csa_guzzle.client_manager')->createClient('dynamic_name');
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 }
Async Requests: Use promises for async operations:
$promise = $client->getAsync('endpoint');
$promise->then(function ($response) {
// Handle response
});
csa_guzzle:
clients:
api:
cache: cache.app
csa_guzzle:
clients:
api:
middleware: ['csa_guzzle.middleware.monolog']
config/packages/dev/csa_guzzle.yaml):
csa_guzzle:
clients:
api:
base_url: '%env(API_URL)%'
Deprecated Guzzle Version:
Configuration Overrides:
config/packages/csa_guzzle.yaml is merged with defaults. Overrides may not work as expected.!important in YAML or set defaults in config/packages/overrides/csa_guzzle.yaml.Middleware Conflicts:
logger or monolog may not be maintained. Custom middleware might be needed.var/log/dev.log for Guzzle events if middleware fails silently.Service Autowiring:
services.yaml:
services:
Csa\GuzzleBundle\Client\ClientInterface: '@csa_guzzle.client.api'
Deprecated Symfony Components:
Symfony\Component\HttpFoundation). Test thoroughly in newer Symfony versions.Enable Guzzle Debug: Add debug middleware temporarily:
$client->getEmitter()->attach(
new \GuzzleHttp\Middleware::tap(function ($request) {
error_log('Request: ' . $request->getUri());
})
);
Check Event Dispatcher: Ensure events are subscribed correctly:
bin/console debug:event-dispatcher | grep csa_guzzle
Validate Config: Use Symfony’s config validator:
bin/console config:validate csa_guzzle
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'
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']
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]);
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);
How can I help you explore Laravel packages today?