Installation Add the package via Composer (note: this is for Guzzle 3, which is outdated; ensure compatibility with your Laravel version):
composer require guzzle/plugin:^3.0
Check Laravel's Guzzle HTTP client version (vendor/guzzlehttp/guzzle) to confirm compatibility.
Basic Usage Register a plugin with Guzzle’s client:
use Guzzle\Plugin\PluginInterface;
use Guzzle\Plugin\BeforePluginInterface;
use Guzzle\Http\Message\RequestInterface;
$client = new \Guzzle\Http\Client();
$client->addSubscriber(new class implements BeforePluginInterface {
public function before(RequestInterface $request) {
// Modify request (e.g., add headers)
$request->getHeaders()->add('X-Custom-Header', 'value');
}
});
First Use Case Use a plugin to log requests/responses for debugging:
$client->addSubscriber(new \Guzzle\Plugin\Log\LogPlugin());
Request/Response Modification
Use BeforePluginInterface/AfterPluginInterface to intercept and alter requests/responses:
$client->addSubscriber(new class implements AfterPluginInterface {
public function after($event, $request) {
if ($event['result'] instanceof \Guzzle\Http\Message\Response) {
$response = $event['result'];
// Parse JSON response
$data = json_decode($response->getBody(), true);
// Modify data before returning
}
}
});
Middleware-Like Behavior Chain plugins for layered functionality (e.g., auth + caching):
$client->addSubscriber(new AuthPlugin());
$client->addSubscriber(new CachePlugin());
Laravel Integration
Extend Laravel’s HTTP client (app/Http/Client.php):
$client = app('http_client');
$client->getClient()->addSubscriber(new CustomPlugin());
$this->app->singleton('custom.plugin', function () {
return new CustomPlugin();
});
config/services.php:
'plugins' => [
'auth' => [
'token' => env('API_TOKEN'),
],
],
$mockPlugin = $this->getMockBuilder(CustomPlugin::class)
->disableOriginalConstructor()
->getMock();
$client->getClient()->addSubscriber($mockPlugin);
Guzzle 3 Deprecation
guzzlehttp/guzzle plugins (e.g., guzzlehttp/middleware) instead.Plugin Order Matters
AfterPluginInterface carefully to avoid race conditions.Memory Leaks
Guzzle\Plugin\Log\LogPlugin to inspect request/response cycles:
$client->addSubscriber(new \Guzzle\Plugin\Log\LogPlugin([
'log' => \Monolog\Logger::getInstance('guzzle'),
]));
Guzzle\Plugin\Event for domain-specific logic:
class CustomEvent extends \Guzzle\Plugin\Event {
public function __construct($request, $response, $data) {
parent::__construct($request, $response);
$this->data = $data;
}
}
$client->addSubscriber(new class implements SubscriberInterface {
public function handle($event) {
(new AuthPlugin())->handle($event);
(new CachePlugin())->handle($event);
}
});
event(new RequestHandled($request, $response));
How can I help you explore Laravel packages today?