manager.php 2.4 KB

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