缓存PDO预处理语句我在更新旧(乱)的请求mysql_query)代码(以PDO的过程。在类包装
据我所知,使用预处理语句是良好的安全性和性能,但是在性能方面开始发挥作用时,准备必须完成之后先多执行。这意味着我的代码中的主要重写可能不值得提高性能,但是我想知道我是否可以以另一种方式做到这一点。
我提出的解决办法是包裹PDO类,如下所示:
class PDOCached extends PDO {
private $PreparedStatementCache;
public function prepare($query) {
if (!isset($this->PreparedStatementCache[$query])) {
$this->PreparedStatementCache[$query]=parent::prepare($query);
}
return $this->PreparedStatementCache[$query];
}
}
它的工作原理(即我得到同样的结果。),但我并不清楚它是否可以让我有机可乘性能提升。任何反馈/评论赞赏。
注:我知道这并没有考虑到$ driver_options,但这项工作是不是很重要。
UPDATE:
我已经修改了类,使缓存可选:
class PDOCached extends PDO {
private $PreparedStatementCache;
// WARNING: Does not take into account $driver_options
public function prepare($query, $cached=false) {
if (!$cached) return parent::prepare($query);
if (!isset($this->PreparedStatementCache[$query])) {
// WARNING: Assumes try/catch error handling
$this->PreparedStatementCache[$query]=parent::prepare($query);
}
return $this->PreparedStatementCache[$query];
}
}
典型的web应用很少运行中处理单一请求类似的查询。你确定你有这种情况吗?你不觉得如何使用JOIN或IN来重写它们吗? –
我有一些地方有一个循环根据上下文调用几个不同的函数之一。在这些功能中,特定记录的数据将被检索并格式化以供演示。重写代码或在循环外部移动准备语句将是一件大事,所以我正在寻找这样的替代方案。 –