【发布时间】:2013-08-24 18:13:56
【问题描述】:
我知道使用 orm 会更好,我计划在未来使用它。 但就目前而言,我正在使用这样的结构:
带有标题和日期的北极类 数据库操作的 DataArticle 类 所以我没有在我的文章类中执行我的数据库操作,而是在一个单独的数据类中。
现在,在我所有的 Data.. 类中,我使用代码来执行这样的数据库操作:
public function getArticle($id){
$query = "SELECT title,date from articles where id = ?";
if ($stmt = $this->database->getConnection()->prepare($query)) {
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->bind_result($title,$date);
$stmt->store_result();
$stmt->fetch();
if(($stmt->num_rows) == 1){
$article = new Article();
$article->title = $title;
$article->date = $date;
$stmt->close();
return $article;
}else{
$stmt->close();
return null;
}
}else{
throw new Exception($this->database->getConnection()->error);
}
}
但是以这种方式工作意味着在我的数据类中的每个函数中,我都会连接、执行语句并抛出错误。 这是很多可以使用包装器集中的重复代码。
现在我按照建议 (Throw an exception in a function or how to do descent error handling) 创建一个数据库包装器/处理程序来执行所有数据库内容,因此它们都集中在一个类中,这样更易于维护。
所以我创建了这个类来开始使用 PDO:
<?php
class DatabasePDO
{
private $connection;
private $host = "";
private $username = "";
private $password = "";
private $dbname = "";
public function openConnection(){
$this->connection = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username,$this->password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function getConnection(){
return $this->connection;
}
public function closeConnection(){
$this->connection = null;
}
public function insert($query, array $data){
$this->connection->prepare($query)->execute($data);
return $this->connection->lastInsertId();
}
public function update($query, array $data) {
$stmt = $this->connection->prepare($query);
$stmt->execute($data);
return $stmt->rowCount();
}
public function delete($query, array $data) {
$stmt = $this->connection->prepare($query);
$stmt->execute($data);
return $stmt->rowCount();
}
public function findOne($query, array $data = null){
$sth = $this->connection->prepare($query);
if($data != null){
$sth->execute($data);
}else{
$sth->execute();
}
if($sth->rowCount() == 1){
return $sth->fetchObject();
}else{
return null;
}
}
public function find($query, array $data = null){
$sth = $this->connection->prepare($query);
if($data != null){
$sth->execute($data);
}else{
$sth->execute();
}
if($sth->rowCount() > 0){
while($res = $sth->fetchObject()){
$results[] = $res;
}
return $results;
}else{
return null;
}
}
}
?>
但在阅读一些文章时,我发现这不是一个好习惯,因为 PDO 已经是一个数据库包装器。
但是,通过代码比以前更具可读性。 现在只是
public function getArticle($id){
$article = $this->database->find("select name, date from articles ?",array($id));
$article = new article($article->name, $article->date);
return $article;
}
这段代码要短得多,并且所有数据库逻辑都在 PDO 包装器类中处理,否则我将不得不在每个函数中重复包装器的代码,我的代码将出现在很多地方而不是一个包装器中。
那么有没有更好的方法来使用我的代码,或者它是我使用它的好方法。
【问题讨论】: