saeedhosan / guzzle-handler
The package adds middlewire to laravel event for http client
Requires
- php: ^8.2.0
- guzzlehttp/guzzle: ^7.9.3
- laravel/framework: ^11.0|^12.0|^13.0
Requires (Dev)
- laravel/pint: *
- orchestra/testbench: ^9.0|^10.0|^11.0
- pestphp/pest: ^3.8.2|^4.0.0
- pestphp/pest-plugin-arch: *
- phpstan/phpstan: *
- symfony/var-dumper: *
README
A Guzzle handler and middleware that dispatches Laravel HTTP Client events.
Introduction
This package provides a Guzzle handler that automatically dispatches standard Laravel HTTP client events (RequestSending, ResponseReceived, ConnectionFailed) when making requests. This allows you to leverage Laravel's built-in event listeners, logging, and monitoring even when using a custom Guzzle client instead of the Http facade.
Requirements
- PHP ^8.2
- Guzzle ^7.9
- Laravel Framework ^11.0, ^12.0, or ^13.0
Installation
Install the package via composer:
composer require saeedhosan/guzzle-handler
Usages
Using the HttpClientEvent Handler
The HttpClientEvent handler can be used to wrap an existing Guzzle handler (like CurlHandler or MockHandler) to ensure Laravel events are dispatched.
use GuzzleHttp\Client; use SaeedHosan\GuzzleHandler\Handlers\HttpClientEvent; $handler = HttpClientEvent::make() ->withHandler(new \GuzzleHttp\Handler\CurlHandler()); $client = new Client([ 'handler' => $handler, ]); // This request will now dispatch RequestSending and ResponseReceived events $client->get('https://example.com');
Using mapFailure Middleware
You can also use the Middleware::mapFailure to handle request rejections with a custom callback:
use GuzzleHttp\HandlerStack; use SaeedHosan\GuzzleHandler\Middleware; $stack = HandlerStack::create(); $stack->push(Middleware::mapFailure(function ($reason) { // Handle the failure (e.g., log it or increment a counter) })); $client = new Client(['handler' => $stack]);
Testing
Run the tests using the following command:
composer test