Created
November 30, 2016 16:10
-
-
Save christeredvartsen/64a3a409db251f316d704aed74a95209 to your computer and use it in GitHub Desktop.
Add middleware to Guzzle-6 that removes itself after the first run
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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