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.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\HandlerStack;
  3. use GuzzleHttp\Handler\CurlHandler;
  4. $handler = new CurlHandler();
  5. $stack = HandlerStack::create($handler); // Wrap w/ middleware
  6. $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:

  1. Sending request:
  1. 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.
  2. allow_redirects - No op when sending a request. Following redirects occurs when a response promise is being returned up the stack.
  3. cookies - Adds cookies to requests.
  4. prepare_body - The body of an HTTP request will be prepared (e.g., add default headers like Content-Length, Content-Type, etc.).
  5. <send request with handler>
  1. Processing response:
  1. prepare_body - no op on response processing.
  2. cookies - extracts response cookies into the cookie jar.
  3. allow_redirects - Follows redirects.
  4. 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.