ConnectionResolver.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Database;
  12. class ConnectionResolver implements ConnectionResolverInterface
  13. {
  14. /**
  15. * All the registered connections.
  16. */
  17. protected array $connections = [];
  18. /**
  19. * The default connection name.
  20. */
  21. protected string $default = 'default';
  22. /**
  23. * Create a new connection resolver instance.
  24. */
  25. public function __construct(array $connections = [])
  26. {
  27. foreach ($connections as $name => $connection) {
  28. $this->addConnection($name, $connection);
  29. }
  30. }
  31. /**
  32. * Get a database connection instance.
  33. */
  34. public function connection(?string $name = null): ConnectionInterface
  35. {
  36. if (is_null($name)) {
  37. $name = $this->getDefaultConnection();
  38. }
  39. return $this->connections[$name];
  40. }
  41. /**
  42. * Add a connection to the resolver.
  43. *
  44. * @param string $name
  45. */
  46. public function addConnection($name, ConnectionInterface $connection)
  47. {
  48. $this->connections[$name] = $connection;
  49. }
  50. /**
  51. * Check if a connection has been registered.
  52. *
  53. * @param string $name
  54. */
  55. public function hasConnection($name): bool
  56. {
  57. return isset($this->connections[$name]);
  58. }
  59. /**
  60. * Get the default connection name.
  61. */
  62. public function getDefaultConnection(): string
  63. {
  64. return $this->default;
  65. }
  66. /**
  67. * Set the default connection name.
  68. */
  69. public function setDefaultConnection(string $name): void
  70. {
  71. $this->default = $name;
  72. }
  73. }