在处理特定应用程序时,我不断地编写非常相似的查询,一次又一次。它们并不完全相同,但形式非常相似,并且嵌入到几乎相同的代码块中,例如,
$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 吗?编写一个类来执行这种查询(使用表、列、绑定(bind)变量等的构造函数参数或 setter )然后在我的应用程序中重复使用它似乎没有意义。但与此同时,我无法摆脱这种我在重复自己的唠叨感觉。
也许只是因为编写简单查询的方法只有那么多种,所以像这样一定程度的重复是可以预料的。
想法?
最佳答案
很多人都这样做。创建一个代表每个表的类,所有表都继承自同一个类。基类可以处理加载和保存数据。所以如果你想加载数据,你只需要调用加载方法。您可以通过对象的属性设置和访问字段值。
还有类似 hibernate 的库为你处理很多脏活累活。
关于mysql - DRY 和类似查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/593249/