mysql - DRY 和类似查询

标签 mysql dry

在处理特定应用程序时,我不断地编写非常相似的查询,一次又一次。它们并不完全相同,但形式非常相似,并且嵌入到几乎相同的代码块中,例如

$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/

相关文章:

mysql - SQL继承性能

mysql table trigger throughs错误

ruby-on-rails - 如何对我的 Rails 应用程序的 CRUD 部分进行 DRY?

java - 使用 Java 注解消除重复

mysql - 选择 "all"同时在mysql中选择 "individually"

php - 负载平衡服务器的文件上传最佳解决方案

asp.net-mvc-3 - MVC3 和 KnockoutJS DRYly

ruby-on-rails - 是否有在 RAILS API Controller 索引操作中应用过滤器哈希的 DRY 方法?

java - 当需要在每个 setter 中使用相同的条件运算符时如何保持干燥?

PHP 应用程序未将数据保存到 MySQL 数据库