PDO.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Simps.
  5. *
  6. * @link https://simps.io
  7. * @document https://doc.simps.io
  8. * @license https://github.com/simple-swoole/simps/blob/master/LICENSE
  9. */
  10. namespace Simps\DB;
  11. use RuntimeException;
  12. use Swoole\Database\PDOConfig;
  13. use Swoole\Database\PDOPool;
  14. class PDO
  15. {
  16. protected $pools;
  17. /**
  18. * @var array
  19. */
  20. protected $config = [
  21. 'host' => 'localhost',
  22. 'port' => 3306,
  23. 'database' => 'test',
  24. 'username' => 'root',
  25. 'password' => 'root',
  26. 'charset' => 'utf8mb4',
  27. 'unixSocket' => null,
  28. 'options' => [],
  29. 'size' => 64,
  30. ];
  31. private static $instance;
  32. private function __construct(array $config)
  33. {
  34. if (empty($this->pools)) {
  35. $this->config = array_replace_recursive($this->config, $config);
  36. $this->pools = new PDOPool(
  37. (new PDOConfig())
  38. ->withHost($this->config['host'])
  39. ->withPort($this->config['port'])
  40. ->withUnixSocket($this->config['unixSocket'])
  41. ->withDbName($this->config['database'])
  42. ->withCharset($this->config['charset'])
  43. ->withUsername($this->config['username'])
  44. ->withPassword($this->config['password'])
  45. ->withOptions($this->config['options']),
  46. $this->config['size']
  47. );
  48. }
  49. }
  50. public static function getInstance($config = null)
  51. {
  52. if (empty(self::$instance)) {
  53. if (empty($config)) {
  54. throw new RuntimeException('pdo config empty');
  55. }
  56. if (empty($config['size'])) {
  57. throw new RuntimeException('the size of database connection pools cannot be empty');
  58. }
  59. self::$instance = new static($config);
  60. }
  61. return self::$instance;
  62. }
  63. public function getConnection()
  64. {
  65. return $this->pools->get();
  66. }
  67. public function close($connection = null)
  68. {
  69. $this->pools->put($connection);
  70. }
  71. }