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