HandlerStack

A handler stack represents a stack of middleware to apply to a base handler function. You can push middleware to the stack to add to the top of the stack, and unshift middleware onto the stack to add to the bottom of the stack. When the stack is resolved, the handler is pushed onto the stack. Each value is then popped off of the stack, wrapping the previous value popped off of the stack.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\HandlerStack;
  3. use GuzzleHttp\Middleware;
  4. use GuzzleHttp\Utils;
  5. use Psr\Http\Message\RequestInterface;
  6. $stack = new HandlerStack();
  7. $stack->setHandler(Utils::chooseHandler());
  8. $stack->push(Middleware::mapRequest(function (RequestInterface $r) {
  9. echo 'A';
  10. return $r;
  11. }));
  12. $stack->push(Middleware::mapRequest(function (RequestInterface $r) {
  13. echo 'B';
  14. return $r;
  15. }));
  16. $stack->push(Middleware::mapRequest(function (RequestInterface $r) {
  17. echo 'C';
  18. return $r;
  19. }));
  20. $client->request('GET', 'http://httpbin.org/');
  21. // echoes 'ABC';
  22. $stack->unshift(Middleware::mapRequest(function (RequestInterface $r) {
  23. echo '0';
  24. return $r;
  25. }));
  26. $client = new Client(['handler' => $stack]);
  27. $client->request('GET', 'http://httpbin.org/');
  28. // echoes '0ABC';

You can give middleware a name, which allows you to add middleware before other named middleware, after other named middleware, or remove middleware by name.

  1. use Psr\Http\Message\RequestInterface;
  2. use GuzzleHttp\Middleware;
  3. // Add a middleware with a name
  4. $stack->push(Middleware::mapRequest(function (RequestInterface $r) {
  5. return $r->withHeader('X-Foo', 'Bar');
  6. }, 'add_foo'));
  7. // Add a middleware before a named middleware (unshift before).
  8. $stack->before('add_foo', Middleware::mapRequest(function (RequestInterface $r) {
  9. return $r->withHeader('X-Baz', 'Qux');
  10. }, 'add_baz'));
  11. // Add a middleware after a named middleware (pushed after).
  12. $stack->after('add_baz', Middleware::mapRequest(function (RequestInterface $r) {
  13. return $r->withHeader('X-Lorem', 'Ipsum');
  14. }));
  15. // Remove a middleware by name
  16. $stack->remove('add_foo');