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.6 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 = null, $config = null)
  32. {
  33. if ($name === null) {
  34. $name = 'default';
  35. }
  36. if (! isset(self::$connections[$name])) {
  37. if (!$config) {
  38. $config = Config::get('databases')->$name;
  39. }
  40. if (! is_array($config)) {
  41. throw new Exception('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 Exception('Database driver must extends DbDriver');
  51. }
  52. self::$connections[$name] = $connection;
  53. }
  54. return self::$connections[$name];
  55. }
  56. }