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.

63 lines
1.8 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. }