Using Guzzle 6 Middleware in a Laravel Application
The most significant change between Guzzle 5 and 6 is moving away from the event system I grew so accustomed to in Version 5 to middleware in version 6. Needless to say, it was a big adjustment for me at first and it felt like a downgrade. After my initial grumbling, the upgrade guide explains the reasoning for the change:
Instead of using the event system to listen for things like the before event, you now create a stack based middleware function that intercepts a request on the way in and the promise of the response on the way out. This is a much simpler and more predictable approach than the event system and works nicely with PSR-7 middleware.
I prefer to keep my dependencies as up-to-date as possible so I decided to learn Guzzle 6 and become more familiar with the middleware. The concepts are pretty straightforward and I have a few patterns that I like to use when building out middleware within my Laravel applications.
I actually had a real need to build out HMAC. The following code illustrates how you might go about building HMAC authorization by sending a signed
Authorization header with a Guzzle middleware:
The middleware uses PHP’s
__invoke magic method and includes a couple service dependencies that can come from a service container, configuration, etc. With this middleware, Guzzle might send something similiar to the following header:
Authorization: Signature keyId="key",algorithm="hmac-sha1",signature="za3U%2BbsQX4otneqSfYZuJuZP%2FrY%3D"
Next, you can resolve tagged middleware with Laravel’s service container:
In a real application, you would pass configuration values into the middleware constructor, but
secret are just to simplify the example. To experiment with your new middleware, create a simple route in
routes/web.php that you can send requests to:
Now try it out with
php artisan tinker:
Boom! This is a simple example, but you could also tag multiple groups of middleware that you can mix and match within various HTTP clients!
Originally published at bitpress.io on April 7, 2017.