Guzzle clients use a handler and middleware system to send HTTP requests.
A handler function accepts aPsr\Http\Message\RequestInterface
and array ofrequest options and returns aGuzzleHttp\Promise\PromiseInterface
that isfulfilled with aPsr\Http\Message\ResponseInterface
or rejected with anexception.
You can provide a custom handler to a client using thehandler
option ofa client constructor. It is important to understand that several requestoptions used by Guzzle require that specific middlewares wrap the handler usedby the client. You can ensure that the handler you provide to a client uses thedefault middlewares by wrapping the handler in theGuzzleHttp\HandlerStack::create(callable$handler=null)
static method.
useGuzzleHttp\Client;useGuzzleHttp\HandlerStack;useGuzzleHttp\Handler\CurlHandler;$handler=newCurlHandler();$stack=HandlerStack::create($handler);// Wrap w/ middleware$client=newClient(['handler'=>$stack]);
Thecreate
method adds default handlers to theHandlerStack
. When theHandlerStack
is resolved, the handlers will execute in the following order:
http_errors
- No op when sending a request. The response status codeis checked in the response processing when returning a response promise upthe stack.allow_redirects
- No op when sending a request. Following redirectsoccurs when a response promise is being returned up the stack.cookies
- Adds cookies to requests.prepare_body
- The body of an HTTP request will be prepared (e.g.,add default headers like Content-Length, Content-Type, etc.).- <send request with handler>
prepare_body
- no op on response processing.cookies
- extracts response cookies into the cookie jar.allow_redirects
- Follows redirects.http_errors
- throws exceptions when the response status code>=
400.
When provided no$handler
argument,GuzzleHttp\HandlerStack::create()
will choose the most appropriate handler based on the extensions available onyour system.
Important
The handler provided to a client determines how request options are appliedand utilized for each request sent by a client. For example, if you do nothave a cookie middleware associated with a client, then setting thecookies
request option will have no effect on the request.
Middleware augments the functionality of handlers by invoking them in theprocess of generating responses. Middleware is implemented as a higher orderfunction that takes the following form.
usePsr\Http\Message\RequestInterface;functionmy_middleware(){returnfunction(callable$handler){returnfunction(RequestInterface$request,array$options)use($handler){return$handler($request,$options);};};}
Middleware functions return a function that accepts the next handler to invoke.This returned function then returns another function that acts as a composedhandler-- it accepts a request and options, and returns a promise that isfulfilled with a response. Your composed middleware can modify the request,add custom request options, and modify the promise returned by the downstreamhandler.
Here's an example of adding a header to each request.
usePsr\Http\Message\RequestInterface;functionadd_header($header,$value){returnfunction(callable$handler)use($header,$value){returnfunction(RequestInterface$request,array$options)use($handler,$header,$value){$request=$request->withHeader($header,$value);return$handler($request,$options);};};}
Once a middleware has been created, you can add it to a client by eitherwrapping the handler used by the client or by decorating a handler stack.
useGuzzleHttp\HandlerStack;useGuzzleHttp\Handler\CurlHandler;useGuzzleHttp\Client;$stack=newHandlerStack();$stack->setHandler(newCurlHandler());$stack->push(add_header('X-Foo','bar'));$client=newClient(['handler'=>$stack]);
Now when you send a request, the client will use a handler composed with youradded middleware, adding a header to each request.
Here's an example of creating a middleware that modifies the response of thedownstream handler. This example adds a header to the response.
usePsr\Http\Message\RequestInterface;usePsr\Http\Message\ResponseInterface;useGuzzleHttp\HandlerStack;useGuzzleHttp\Handler\CurlHandler;useGuzzleHttp\Client;functionadd_response_header($header,$value){returnfunction(callable$handler)use($header,$value){returnfunction(RequestInterface$request,array$options)use($handler,$header,$value){$promise=$handler($request,$options);return$promise->then(function(ResponseInterface$response)use($header,$value){return$response->withHeader($header,$value);});};};}$stack=newHandlerStack();$stack->setHandler(newCurlHandler());$stack->push(add_response_header('X-Foo','bar'));$client=newClient(['handler'=>$stack]);
Creating a middleware that modifies a request is made much simpler using theGuzzleHttp\Middleware::mapRequest()
middleware. This middleware acceptsa function that takes the request argument and returns the request to send.
usePsr\Http\Message\RequestInterface;useGuzzleHttp\HandlerStack;useGuzzleHttp\Handler\CurlHandler;useGuzzleHttp\Client;useGuzzleHttp\Middleware;$stack=newHandlerStack();$stack->setHandler(newCurlHandler());$stack->push(Middleware::mapRequest(function(RequestInterface$request){return$request->withHeader('X-Foo','bar');}));$client=newClient(['handler'=>$stack]);
Modifying a response is also much simpler using theGuzzleHttp\Middleware::mapResponse()
middleware.
usePsr\Http\Message\ResponseInterface;useGuzzleHttp\HandlerStack;useGuzzleHttp\Handler\CurlHandler;useGuzzleHttp\Client;useGuzzleHttp\Middleware;$stack=newHandlerStack();$stack->setHandler(newCurlHandler());$stack->push(Middleware::mapResponse(function(ResponseInterface$response){return$response->withHeader('X-Foo','bar');}));$client=newClient(['handler'=>$stack]);
A handler stack represents a stack of middleware to apply to a base handlerfunction. 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. Whenthe stack is resolved, the handler is pushed onto the stack. Each value isthen popped off of the stack, wrapping the previous value popped off of thestack.
useGuzzleHttp\Client;useGuzzleHttp\HandlerStack;useGuzzleHttp\Middleware;useGuzzleHttp\Utils;usePsr\Http\Message\RequestInterface;$stack=newHandlerStack();$stack->setHandler(Utils::chooseHandler());$stack->push(Middleware::mapRequest(function(RequestInterface$r){echo'A';return$r;}));$stack->push(Middleware::mapRequest(function(RequestInterface$r){echo'B';return$r;}));$stack->push(Middleware::mapRequest(function(RequestInterface$r){echo'C';return$r;}));$client->request('GET','http://httpbin.org/');// echoes 'ABC';$stack->unshift(Middleware::mapRequest(function(RequestInterface$r){echo'0';return$r;}));$client=newClient(['handler'=>$stack]);$client->request('GET','http://httpbin.org/');// echoes '0ABC';
You can give middleware a name, which allows you to add middleware beforeother named middleware, after other named middleware, or remove middlewareby name.
usePsr\Http\Message\RequestInterface;useGuzzleHttp\Middleware;// Add a middleware with a name$stack->push(Middleware::mapRequest(function(RequestInterface$r){return$r->withHeader('X-Foo','Bar');},'add_foo'));// Add a middleware before a named middleware (unshift before).$stack->before('add_foo',Middleware::mapRequest(function(RequestInterface$r){return$r->withHeader('X-Baz','Qux');},'add_baz'));// Add a middleware after a named middleware (pushed after).$stack->after('add_baz',Middleware::mapRequest(function(RequestInterface$r){return$r->withHeader('X-Lorem','Ipsum');}));// Remove a middleware by name$stack->remove('add_foo');
As stated earlier, a handler is a function accepts aPsr\Http\Message\RequestInterface
and array of request options and returnsaGuzzleHttp\Promise\PromiseInterface
that is fulfilled with aPsr\Http\Message\ResponseInterface
or rejected with an exception.
A handler is responsible for applying the followingRequest Options.These request options are a subset of request options called"transfer options".