SimpleDebuggableConnection.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 'SharedConfigurations.php';
  11. use Predis\ConnectionParameters;
  12. use Predis\Commands\ICommand;
  13. use Predis\Network\StreamConnection;
  14. class SimpleDebuggableConnection extends StreamConnection
  15. {
  16. private $tstart = 0;
  17. private $debugBuffer = array();
  18. public function connect()
  19. {
  20. $this->tstart = microtime(true);
  21. parent::connect();
  22. }
  23. private function storeDebug(ICommand $command, $direction)
  24. {
  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 writeCommand(ICommand $command)
  34. {
  35. parent::writeCommand($command);
  36. $this->storeDebug($command, '->');
  37. }
  38. public function readResponse(ICommand $command)
  39. {
  40. $reply = parent::readResponse($command);
  41. $this->storeDebug($command, '<-');
  42. return $reply;
  43. }
  44. public function getDebugBuffer()
  45. {
  46. return $this->debugBuffer;
  47. }
  48. }
  49. $options = array(
  50. 'connections' => array(
  51. 'tcp' => 'SimpleDebuggableConnection',
  52. ),
  53. );
  54. $client = new Predis\Client($single_server, $options);
  55. $client->set('foo', 'bar');
  56. $client->get('foo');
  57. $client->info();
  58. print_r($client->getConnection()->getDebugBuffer());
  59. /* OUTPUT:
  60. Array
  61. (
  62. [0] => SELECT 15 -> 127.0.0.1:6379 [0.0008s]
  63. [1] => SELECT 15 <- 127.0.0.1:6379 [0.0012s]
  64. [2] => SET foo -> 127.0.0.1:6379 [0.0014s]
  65. [3] => SET foo <- 127.0.0.1:6379 [0.0014s]
  66. [4] => GET foo -> 127.0.0.1:6379 [0.0016s]
  67. [5] => GET foo <- 127.0.0.1:6379 [0.0018s]
  68. [6] => INFO -> 127.0.0.1:6379 [0.002s]
  69. [7] => INFO <- 127.0.0.1:6379 [0.0025s]
  70. )
  71. */