History Middleware

When using things like the Mock handler, you often need to know if the requests you expected to send were sent exactly as you intended. While the mock handler responds with mocked responses, the history middleware maintains a history of the requests that were sent by a client.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\HandlerStack;
  3. use GuzzleHttp\Middleware;
  4. $container = [];
  5. $history = Middleware::history($container);
  6. $stack = HandlerStack::create();
  7. // Add the history middleware to the handler stack.
  8. $stack->push($history);
  9. $client = new Client(['handler' => $stack]);
  10. $client->request('GET', 'http://httpbin.org/get');
  11. $client->request('HEAD', 'http://httpbin.org/get');
  12. // Count the number of transactions
  13. echo count($container);
  14. //> 2
  15. // Iterate over the requests and responses
  16. foreach ($container as $transaction) {
  17. echo $transaction['request']->getMethod();
  18. //> GET, HEAD
  19. if ($transaction['response']) {
  20. echo $transaction['response']->getStatusCode();
  21. //> 200, 200
  22. } elseif ($transaction['error']) {
  23. echo $transaction['error'];
  24. //> exception
  25. }
  26. var_dump($transaction['options']);
  27. //> dumps the request options of the sent request.
  28. }