Skip to content

Instantly share code, notes, and snippets.

@christeredvartsen
Created November 30, 2016 16:10
Show Gist options
  • Save christeredvartsen/64a3a409db251f316d704aed74a95209 to your computer and use it in GitHub Desktop.
Save christeredvartsen/64a3a409db251f316d704aed74a95209 to your computer and use it in GitHub Desktop.
Add middleware to Guzzle-6 that removes itself after the first run
<?php
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Client;
use Psr\Http\Message\RequestInterface;
// Create a default stack
$stack = HandlerStack::create();
// Create the middleware
$middlewareName = 'some-middleware-name';
$middleware = Middleware::mapRequest(function (RequestInterface $request) use ($stack, $middlewareName) {
// ...
var_dump('Hi!');
// Remove this middleware
$stack->remove($middlewareName);
// ...
return $request;
});
// Push the named middleware onto the stack
$stack->push($middleware, $middlewareName);
// Create a client
$client = new Client(['handler' => $stack]);
$client->get('https://example.com'); // string(3) "Hi!"
$client->get('https://example.com'); // var_dump not executed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment