Caching regular SQL queries is simple enough.
public function query($sql) {
if( $result = cache::get(sha1($sql)) ) {
return $result;
}
$result = $this->connection->query($sql);
cache::set(sha1($sql), $result);
return $result;
}
But how do you cache queries with prepared statements since you don't know what the query will be until after the statement is already prepared and then the data is bound?
$sth = $dbh->prepare('SELECT * FROM table WHERE id = ?');
...later...
$sth->bindParam(1, $id);
$sth->execute();
I get the feeling that this is a two-part answer: First, the statements are cached in per-page memory (like an array of $this->statements[]) since the database resource ids won't last long and can't be stored in files or anything.
Second, before the statements are executed() we look in memcached/filecache for the results by hashing the sql used to create the statement (easy with PDOStatement::queryString
) plus the hashes of the params given. The trouble is finding the params in the statement object.
Of course, this is just one idea and there are probably better solutions.