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

12 years ago
12 years ago
  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 Redis[]
  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. * @throws GeneralException
  26. * @return Redis
  27. */
  28. static public function connect($name = 'default', $config = null)
  29. {
  30. if (!isset(self::$connections[$name])) {
  31. if (!$config) {
  32. if (!is_object(Config::get('Redis'))) {
  33. throw new GeneralException('Redis config no existence');
  34. }
  35. $config = Config::get('Redis')->$name;
  36. }
  37. if (!is_array($config)) {
  38. throw new GeneralException('Connection parameters must be an array');
  39. }
  40. $host = isset($config['host']) ? $config['host'] : 'localhost';
  41. $port = isset($config['port']) ? $config['port'] : 6379;
  42. $database = isset($config['database']) ? $config['database'] : 0;
  43. /**
  44. * @var Redis
  45. */
  46. $connection = new Redis();
  47. if (Config::get('PROFILER_DETAILS')) {
  48. $connection = new RedisDebug($connection);
  49. }
  50. if (!$connection->connect($host, $port)) {
  51. throw new GeneralException('Failed to connect to Redis server at ' . $host . ':' . $port);
  52. }
  53. if ($database) {
  54. if (!$connection->select($database)) {
  55. throw new GeneralException('Failed to select Redis database with index ' . $database);
  56. }
  57. }
  58. self::$connections[$name] = $connection;
  59. }
  60. return self::$connections[$name];
  61. }
  62. }