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.

64 lines
1.8 KiB

  1. <?php
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage db
  7. * @since 2010-02-16
  8. * @version SVN: $Id$
  9. * @filesource $URL$
  10. */
  11. class Db
  12. {
  13. const FETCH_ASSOC = 2;
  14. const FETCH_NUM = 3;
  15. const FETCH_BOTH = 4;
  16. const FETCH_OBJ = 5;
  17. /**
  18. * Databases connections
  19. *
  20. * @var array
  21. */
  22. static protected $connections = array();
  23. /**
  24. * Connect to database
  25. *
  26. * @param string $name Database name. If not set 'default' will be used.
  27. * @param array $config Configuration array.
  28. *
  29. * @return DbDriver
  30. * @throws InitializationException
  31. */
  32. static public function connect($name = 'default', $config = null)
  33. {
  34. if (!isset(self::$connections[$name])) {
  35. if (!$config) {
  36. if (!is_object(Config::get(__CLASS__))) {
  37. throw new InitializationException('Trying to get property of non-object');
  38. }
  39. $config = Config::get(__CLASS__)->$name;
  40. }
  41. if (!is_array($config)) {
  42. throw new InitializationException('Connection parameters must be an array');
  43. }
  44. $driver = 'MySQLiDriver';
  45. if (isset($config['driver'])) {
  46. $driver = $config['driver'];
  47. unset($config['driver']);
  48. }
  49. $connection = new $driver($config);
  50. if (!$connection instanceof DbDriver) {
  51. throw new InitializationException('Database driver must extends DbDriver');
  52. }
  53. self::$connections[$name] = $connection;
  54. }
  55. return self::$connections[$name];
  56. }
  57. }