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.

67 lines
2.0 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. if (gettype(Config::get('Redis')) != 'object') {
  32. throw new GeneralException('Redis config no existence');
  33. }
  34. $config = Config::get('Redis')->$name;
  35. }
  36. if (!is_array($config)) {
  37. throw new GeneralException('Connection parameters must be an array');
  38. }
  39. $host = isset($config['host']) ? $config['host'] : 'localhost';
  40. $port = isset($config['port']) ? $config['port'] : 6379;
  41. $database = isset($config['database']) ? $config['database'] : 0;
  42. /**
  43. * @var Redis
  44. */
  45. $connection = new Redis();
  46. if (defined('DEBUG') && DEBUG == true) {
  47. $connection = new RedisDebug($connection);
  48. }
  49. if (!$connection->connect($host, $port)) {
  50. throw new GeneralException('Failed to connect to Redis server at ' . $host . ':' . $port);
  51. }
  52. if ($database) {
  53. if (!$connection->select($database)) {
  54. throw new GeneralException('Failed to select Redis database with index ' . $database);
  55. }
  56. }
  57. self::$connections[$name] = $connection;
  58. }
  59. return self::$connections[$name];
  60. }
  61. }