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.

63 lines
1.7 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. */
  31. static public function connect($name = 'default', $config = null)
  32. {
  33. if (!isset(self::$connections[$name])) {
  34. if (!$config) {
  35. if (!is_object(Config::get(__CLASS__))) {
  36. throw new InitializationException('Trying to get property of non-object');
  37. }
  38. $config = 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. }