Handlers
A handler function accepts a Psr\Http\Message\RequestInterface
and array of request options and returns a GuzzleHttp\Promise\PromiseInterface
that is fulfilled with a Psr\Http\Message\ResponseInterface
or rejected with an exception.
You can provide a custom handler to a client using the handler
option of a client constructor. It is important to understand that several request options used by Guzzle require that specific middlewares wrap the handler used by the client. You can ensure that the handler you provide to a client uses the default middlewares by wrapping the handler in the GuzzleHttp\HandlerStack::create(callable $handler = null)
static method.
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
$handler = new CurlHandler();
$stack = HandlerStack::create($handler); // Wrap w/ middleware
$client = new Client(['handler' => $stack]);
The create
method adds default handlers to the HandlerStack
. When the HandlerStack
is resolved, the handlers will execute in the following order:
- Sending request:
http_errors
- No op when sending a request. The response status code is checked in the response processing when returning a response promise up the stack.allow_redirects
- No op when sending a request. Following redirects occurs 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>
- Processing response:
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>=
300.
When provided no $handler
argument, GuzzleHttp\HandlerStack::create()
will choose the most appropriate handler based on the extensions available on your system.
重要
The handler provided to a client determines how request options are applied and utilized for each request sent by a client. For example, if you do not have a cookie middleware associated with a client, then setting the cookies
request option will have no effect on the request.