manager.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php namespace Laravel\Database;
  2. class Manager {
  3. /**
  4. * The established database connections.
  5. *
  6. * @var array
  7. */
  8. public $connections = array();
  9. /**
  10. * The database connection configurations.
  11. *
  12. * @var array
  13. */
  14. private $config;
  15. /**
  16. * The default database connection name.
  17. *
  18. * @var string
  19. */
  20. private $default;
  21. /**
  22. * Create a new database manager instance.
  23. *
  24. * @param string $default
  25. */
  26. public function __construct($config, $default)
  27. {
  28. $this->config = $config;
  29. $this->default = $default;
  30. }
  31. /**
  32. * Get a database connection. If no database name is specified, the default
  33. * connection will be returned as defined in the db configuration file.
  34. *
  35. * Note: Database connections are managed as singletons.
  36. *
  37. * @param string $connection
  38. * @return Database\Connection
  39. */
  40. public function connection($connection = null)
  41. {
  42. if (is_null($connection)) $connection = $this->default;
  43. if ( ! array_key_exists($connection, $this->connections))
  44. {
  45. if ( ! isset($this->config[$connection]))
  46. {
  47. throw new \Exception("Database connection [$connection] is not defined.");
  48. }
  49. $connector = Connector\Factory::make($this->config[$connection]);
  50. static::$connections[$connection] = new Connection($connection, $this->config[$connection], $connector);
  51. }
  52. return $this->connections[$connection];
  53. }
  54. /**
  55. * Begin a fluent query against a table.
  56. *
  57. * This method primarily serves as a short-cut to the $connection->table() method.
  58. *
  59. * @param string $table
  60. * @param string $connection
  61. * @return Database\Query
  62. */
  63. public function table($table, $connection = null)
  64. {
  65. return $this->connection($connection)->table($table);
  66. }
  67. /**
  68. * Magic Method for calling methods on the default database connection.
  69. *
  70. * This provides a convenient API for querying or examining the default database connection.
  71. */
  72. public function __call($method, $parameters)
  73. {
  74. return call_user_func_array(array($this->connection(), $method), $parameters);
  75. }
  76. }