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