From 07b73e7f7fa6630fb2d54d0e255642051ab5ba3e Mon Sep 17 00:00:00 2001 From: Dave Smith-Hayes Date: Mon, 23 Sep 2024 19:53:27 -0400 Subject: [PATCH] Get the Pooled connection class set up. --- .../Database/ConnectionPool.php | 10 ++++++++ .../Database/ConnectionPoolConfig.php | 20 ++++++++++++++++ .../Database/PooledConnection.php | 23 +++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 app/src/Infrastructure/Database/PooledConnection.php diff --git a/app/src/Infrastructure/Database/ConnectionPool.php b/app/src/Infrastructure/Database/ConnectionPool.php index 534343f..f059b13 100644 --- a/app/src/Infrastructure/Database/ConnectionPool.php +++ b/app/src/Infrastructure/Database/ConnectionPool.php @@ -2,6 +2,7 @@ namespace Slovocast\Infrastructure\Database; +use React\Mysql\MysqlClient; use Slovocast\Infrastructure\Api\Database\ConnectionPoolInterface; use Slovocast\Infrastructure\Api\Database\PooledConnectionInterface; @@ -13,6 +14,15 @@ class ConnectionPool implements ConnectionPoolInterface const int DEFAULT_WAIT_TIMEOUT = 100; private array $idleConnections; private array $activeConnections; + private ConnectionPoolConfig $config; + + public function __construct(ConnectionPoolConfig $config) + { + $this->config = $config; + for ($i = 0; $i < $config->getTotalConnections(); $i++) { + $this->idleConnections[] = new MysqlClient($this->config->getDsn()); + } + } public function getTotalIdleConnections(): int { diff --git a/app/src/Infrastructure/Database/ConnectionPoolConfig.php b/app/src/Infrastructure/Database/ConnectionPoolConfig.php index 8f15943..2671822 100644 --- a/app/src/Infrastructure/Database/ConnectionPoolConfig.php +++ b/app/src/Infrastructure/Database/ConnectionPoolConfig.php @@ -2,14 +2,18 @@ namespace Slovocast\Infrastructure\Database; +use React\Mysql\MysqlClient; + class ConnectionPoolConfig { public function __construct( public readonly string $username, public readonly string $password, public readonly string $database, + public readonly string $host, protected int $port = 3306, protected int $poolWaitTimeout = ConnectionPool::DEFAULT_WAIT_TIMEOUT, + protected int $totalConnections = 10, ) { } public function getPort(): int @@ -21,4 +25,20 @@ class ConnectionPoolConfig { return $this->poolWaitTimeout; } + + public function getTotalConnections(): int + { + return $this->totalConnections; + } + + public function getDsn(): string + { + return sprintf( + "%s:%s@%s/%s", + rawurlencode($this->username), + rawurlencode($this->password), + $this->host, + $this->database + ); + } } diff --git a/app/src/Infrastructure/Database/PooledConnection.php b/app/src/Infrastructure/Database/PooledConnection.php new file mode 100644 index 0000000..7d16e98 --- /dev/null +++ b/app/src/Infrastructure/Database/PooledConnection.php @@ -0,0 +1,23 @@ +connectionPool = $connectionPool; + return $this; + } + + public function release(): void + { + $this->connectionPool->releaseConnection($this); + } +}