SimpleDebuggableConnection.php 2.1 KB

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