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