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.

65 lines
2.1 KiB

10 years ago
12 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. <?php namespace Majestic\Redis;
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage Redis
  7. * @since 2010-07-17
  8. */
  9. class RedisManager
  10. {
  11. /**
  12. * Redis connections
  13. *
  14. * @var Redis[]
  15. */
  16. static protected $connections = array();
  17. /**
  18. * Connect to redis
  19. *
  20. * @param string $name connection name. If not set 'default' will be used.
  21. * @param array $config Configuration array.
  22. *
  23. * @throws \Majestic\Exception\GeneralException
  24. * @return Redis
  25. */
  26. static public function connect($name = 'default', $config = null)
  27. {
  28. if (!isset(self::$connections[$name])) {
  29. if (!$config) {
  30. if (!is_object(\Majestic\Config::get('Redis'))) {
  31. throw new \Majestic\Exception\GeneralException('Redis config no existence');
  32. }
  33. $config = \Majestic\Config::get('Redis')->$name;
  34. }
  35. if (!is_array($config)) {
  36. throw new \Majestic\Exception\GeneralException('Connection parameters must be an array');
  37. }
  38. $host = isset($config['host']) ? $config['host'] : 'localhost';
  39. $port = isset($config['port']) ? $config['port'] : 6379;
  40. $database = isset($config['database']) ? $config['database'] : 0;
  41. /**
  42. * @var Redis
  43. */
  44. $connection = new \Redis();
  45. if (\Majestic\Config::get('PROFILER_DETAILS')) {
  46. $connection = new RedisDebug($connection);
  47. }
  48. if (!$connection->connect($host, $port)) {
  49. throw new \Majestic\Exception\GeneralException('Failed to connect to Redis server at ' . $host . ':' . $port);
  50. }
  51. if ($database) {
  52. if (!$connection->select($database)) {
  53. throw new \Majestic\Exception\GeneralException('Failed to select Redis database with index ' . $database);
  54. }
  55. }
  56. self::$connections[$name] = $connection;
  57. }
  58. return self::$connections[$name];
  59. }
  60. }