You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.7 KiB

  1. <?php
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage Redis
  7. * @since 2010-07-17
  8. * @version SVN: $Id$
  9. * @filesource $URL$
  10. */
  11. class RedisManager
  12. {
  13. /**
  14. * Redis connections
  15. *
  16. * @var array
  17. */
  18. static protected $connections = array();
  19. /**
  20. * Connect to redis
  21. *
  22. * @param string $name connection name. If not set 'default' will be used.
  23. * @param array $config Configuration array.
  24. *
  25. * @return Redis
  26. */
  27. static public function connect($name = 'default', $config = null)
  28. {
  29. if (!isset(self::$connections[$name])) {
  30. if (!$config) {
  31. $config = Config::get('Redis')->$name;
  32. }
  33. if (!is_array($config)) {
  34. throw new Exception('Connection parameters must be an array');
  35. }
  36. $host = isset($config['host']) ? $config['host'] : 'localhost';
  37. $port = isset($config['port']) ? $config['port'] : 6379;
  38. $database = isset($config['database']) ? $config['database'] : 0;
  39. /**
  40. * @var Redis
  41. */
  42. $connection = new Redis();
  43. if (defined('DEBUG') && DEBUG == true) {
  44. $connection = new RedisDebug($connection);
  45. }
  46. if (!$connection->connect($host, $port)) {
  47. throw new Exception('Failed to connect to Redis server at ' . $host . ':' . $port);
  48. }
  49. if ($database) {
  50. if (!$connection->select($database)) {
  51. throw new Exception('Failed to select Redis database with index ' . $database);
  52. }
  53. }
  54. self::$connections[$name] = $connection;
  55. }
  56. return self::$connections[$name];
  57. }
  58. }
  59. class RedisDebug
  60. {
  61. private $redis;
  62. public function __construct($redis)
  63. {
  64. if (!is_a($redis, 'Redis')) {
  65. throw new MJException();
  66. }
  67. $this->redis = $redis;
  68. }
  69. public function __call($name, $arguments)
  70. {
  71. $command = $name . '(' . $this->r_implode(', ', $arguments) . ')';
  72. $profiler = Profiler::getInstance()->profilerQuery($command);
  73. $data = call_user_func_array(array($this->redis, $name), $arguments);
  74. $profiler->end();
  75. return $data;
  76. }
  77. protected function r_implode($glue, $pieces)
  78. {
  79. $retVal = array();
  80. foreach ($pieces as $r_pieces) {
  81. if (is_array($r_pieces)) {
  82. $retVal[] = '(' . $this->r_implode($glue, $r_pieces) . ')';
  83. } else {
  84. $retVal[] = $r_pieces;
  85. }
  86. }
  87. return implode($glue, $retVal);
  88. }
  89. }