debuggable_connection.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. {
  19. private $tstart = 0;
  20. private $debugBuffer = array();
  21. public function connect()
  22. {
  23. $this->tstart = microtime(true);
  24. parent::connect();
  25. }
  26. private function storeDebug(CommandInterface $command, $direction)
  27. {
  28. $firtsArg = $command->getArgument(0);
  29. $timestamp = round(microtime(true) - $this->tstart, 4);
  30. $debug = $command->getId();
  31. $debug .= isset($firtsArg) ? " $firtsArg " : ' ';
  32. $debug .= "$direction $this";
  33. $debug .= " [{$timestamp}s]";
  34. $this->debugBuffer[] = $debug;
  35. }
  36. public function writeRequest(CommandInterface $command)
  37. {
  38. parent::writeRequest($command);
  39. $this->storeDebug($command, '->');
  40. }
  41. public function readResponse(CommandInterface $command)
  42. {
  43. $response = parent::readResponse($command);
  44. $this->storeDebug($command, '<-');
  45. return $response;
  46. }
  47. public function getDebugBuffer()
  48. {
  49. return $this->debugBuffer;
  50. }
  51. }
  52. $options = array(
  53. 'connections' => array(
  54. 'tcp' => 'SimpleDebuggableConnection',
  55. ),
  56. );
  57. $client = new Predis\Client($single_server, $options);
  58. $client->set('foo', 'bar');
  59. $client->get('foo');
  60. $client->info();
  61. var_export($client->getConnection()->getDebugBuffer());
  62. /* OUTPUT:
  63. array (
  64. 0 => 'SELECT 15 -> 127.0.0.1:6379 [0.0008s]',
  65. 1 => 'SELECT 15 <- 127.0.0.1:6379 [0.001s]',
  66. 2 => 'SET foo -> 127.0.0.1:6379 [0.001s]',
  67. 3 => 'SET foo <- 127.0.0.1:6379 [0.0011s]',
  68. 4 => 'GET foo -> 127.0.0.1:6379 [0.0013s]',
  69. 5 => 'GET foo <- 127.0.0.1:6379 [0.0015s]',
  70. 6 => 'INFO -> 127.0.0.1:6379 [0.0019s]',
  71. 7 => 'INFO <- 127.0.0.1:6379 [0.0022s]',
  72. )
  73. */