45 lines
1 KiB
PHP
45 lines
1 KiB
PHP
<?php
|
|
// DbStatementCache.php
|
|
// Created: 2023-07-21
|
|
// Updated: 2023-07-21
|
|
|
|
namespace Index\Data;
|
|
|
|
/**
|
|
* Container to avoid having many prepared instances of the same query.
|
|
*/
|
|
class DbStatementCache {
|
|
private IDbConnection $dbConn;
|
|
private array $stmts = [];
|
|
|
|
public function __construct(IDbConnection $dbConn) {
|
|
$this->dbConn = $dbConn;
|
|
}
|
|
|
|
private static function hash(string $query): string {
|
|
return hash('xxh3', $query, true);
|
|
}
|
|
|
|
public function get(string $query): IDbStatement {
|
|
$hash = self::hash($query);
|
|
|
|
if(array_key_exists($hash, $this->stmts)) {
|
|
$stmt = $this->stmts[$hash];
|
|
$stmt->reset();
|
|
return $stmt;
|
|
}
|
|
|
|
return $this->stmts[$hash] = $this->dbConn->prepare($query);
|
|
}
|
|
|
|
public function remove(string $query): void {
|
|
unset($this->stmts[self::hash($query)]);
|
|
}
|
|
|
|
public function clear(): void {
|
|
foreach($this->stmts as $stmt)
|
|
$stmt->close();
|
|
$this->stmts = [];
|
|
}
|
|
}
|