index/src/Data/DbStatementCache.php

61 lines
1.5 KiB
PHP

<?php
// DbStatementCache.php
// Created: 2023-07-21
// Updated: 2024-08-03
namespace Index\Data;
/**
* Container to avoid having many prepared instances of the same query.
*/
class DbStatementCache {
/** @var array<string, IDbStatement> */
private array $stmts = [];
/**
* @param IDbConnection $dbConn Connection to use with this cache.
*/
public function __construct(
private IDbConnection $dbConn
) {}
private static function hash(string $query): string {
return hash('xxh3', $query, true);
}
/**
* Gets a cached or creates a new IDbStatement instance.
*
* @param string $query SQL query.
* @return IDbStatement Statement representing the query.
*/
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);
}
/**
* Removes a cached statement from the cache.
*
* @param string $query SQL query of the statement to remove from the cache.
*/
public function remove(string $query): void {
unset($this->stmts[self::hash($query)]);
}
/**
* Closes all statement instances and resets the cache.
*/
public function clear(): void {
foreach($this->stmts as $stmt)
$stmt->close();
$this->stmts = [];
}
}