debuggable_connection.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. require __DIR__.'/shared.php';
  11. // This is an example of how you can easily extend an existing connection class
  12. // and trace the execution of commands for debugging purposes. This can be quite
  13. // useful as a starting poing to understand how your application interacts with
  14. // Redis.
  15. use Predis\Command\CommandInterface;
  16. use Predis\Connection\StreamConnection;
  17. class SimpleDebuggableConnection extends StreamConnection {
  18. private $tstart = 0;
  19. private $debugBuffer = array();
  20. public function connect() {
  21. $this->tstart = microtime(true);
  22. parent::connect();
  23. }
  24. private function storeDebug(CommandInterface $command, $direction) {
  25. $firtsArg = $command->getArgument(0);
  26. $timestamp = round(microtime(true) - $this->tstart, 4);
  27. $debug = $command->getId();
  28. $debug .= isset($firtsArg) ? " $firtsArg " : ' ';
  29. $debug .= "$direction $this";
  30. $debug .= " [{$timestamp}s]";
  31. $this->debugBuffer[] = $debug;
  32. }
  33. public function writeRequest(CommandInterface $command) {
  34. parent::writeRequest($command);
  35. $this->storeDebug($command, '->');
  36. }
  37. public function readResponse(CommandInterface $command) {
  38. $response = parent::readResponse($command);
  39. $this->storeDebug($command, '<-');
  40. return $response;
  41. }
  42. public function getDebugBuffer() {
  43. return $this->debugBuffer;
  44. }
  45. }
  46. $options = array(
  47. 'connections' => array(
  48. 'tcp' => 'SimpleDebuggableConnection',
  49. ),
  50. );
  51. $client = new Predis\Client($single_server, $options);
  52. $client->set('foo', 'bar');
  53. $client->get('foo');
  54. $client->info();
  55. var_export($client->getConnection()->getDebugBuffer());
  56. /* OUTPUT:
  57. array (
  58. 0 => 'SELECT 15 -> 127.0.0.1:6379 [0.0008s]',
  59. 1 => 'SELECT 15 <- 127.0.0.1:6379 [0.001s]',
  60. 2 => 'SET foo -> 127.0.0.1:6379 [0.001s]',
  61. 3 => 'SET foo <- 127.0.0.1:6379 [0.0011s]',
  62. 4 => 'GET foo -> 127.0.0.1:6379 [0.0013s]',
  63. 5 => 'GET foo <- 127.0.0.1:6379 [0.0015s]',
  64. 6 => 'INFO -> 127.0.0.1:6379 [0.0019s]',
  65. 7 => 'INFO <- 127.0.0.1:6379 [0.0022s]',
  66. )
  67. */