manager.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php namespace System\DB;
  2. use System\Config;
  3. class Manager {
  4. /**
  5. * The established database connections.
  6. *
  7. * @var array
  8. */
  9. public static $connections = array();
  10. /**
  11. * Get a database connection. If no database name is specified, the default
  12. * connection will be returned as defined in the db configuration file.
  13. *
  14. * Note: Database connections are managed as singletons.
  15. *
  16. * @param string $connection
  17. * @return Connection
  18. */
  19. public static function connection($connection = null)
  20. {
  21. if (is_null($connection))
  22. {
  23. $connection = Config::get('db.default');
  24. }
  25. if ( ! array_key_exists($connection, static::$connections))
  26. {
  27. $config = Config::get('db.connections');
  28. if ( ! array_key_exists($connection, $config))
  29. {
  30. throw new \Exception("Database connection [$connection] is not defined.");
  31. }
  32. static::$connections[$connection] = new Connection($connection, (object) $config[$connection], new Connector);
  33. }
  34. return static::$connections[$connection];
  35. }
  36. /**
  37. * Begin a fluent query against a table.
  38. *
  39. * @param string $table
  40. * @param string $connection
  41. * @return Query
  42. */
  43. public static function table($table, $connection = null)
  44. {
  45. return static::connection($connection)->table($table);
  46. }
  47. /**
  48. * Magic Method for calling methods on the default database connection.
  49. */
  50. public static function __callStatic($method, $parameters)
  51. {
  52. return call_user_func_array(array(static::connection(), $method), $parameters);
  53. }
  54. }