在一个特定的应用程序上工作,我一次又一次地编写非常相似的查询。它们并不完全相同,但形式非常相似,并且嵌入在几乎相同的代码块中,例如,
$Mysqli = new mysqli;
if ($Stmt = $Mysqli->prepare("SELECT foo
FROM tblFoo
WHERE something = ?")) {
$Stmt->bind_param('s', $this->_something);
$Stmt->execute();
if (0 != $Stmt->errno)
throw new Exception("blah, blah, blah");
$Stmt->bind_result($foo);
while ($Stmt->fetch()){
$this->_foos[] = new Foo($foo);
}
$Stmt->close();
} else {
throw new Exception("blah, blah, blah"););
}
}
后来,在其他地方......
$Mysqli = new mysqli;
if ($Stmt = $Mysqli->prepare("SELECT bar, baz
FROM tblBar
WHERE somethingElse = ?")) {
$Stmt->bind_param('s', $this->_somethingElse);
$Stmt->execute();
if (0 != $Stmt->errno)
throw new Exception("blah, blah, blah");
$Stmt->bind_result($bar, $baz);
while ($Stmt->fetch()){
// do something else with $bar and $baz
}
$Stmt->close();
} else {
throw new Exception("blah, blah, blah"););
}
}
...然后另一个,在其他地方另一个...等等。
这真的违反了 DRY 吗?编写一个类来执行这种查询(使用构造函数参数或表、列、绑定变量等的设置器)然后在我的整个应用程序中重用它似乎没有意义。但与此同时,我无法摆脱这种我在重复自己的唠叨感。
也许只是写一个简单的查询的方法只有这么多,并且像这样的一定数量的重复是可以预料的。
想法?