<?php class DataObject { private $changedFields = array(); // 更新了的字段列表 private $data = array(); // 从PDO取得的一条记录 // 以上几个字段都是本类私有的,因此子类即便是定义同名的属性 // 或者将同名属性关联到数据表的某个字段中,也丝毫不会影响本类的这些变量 function __get($property) { if (isset($this::$_propertyList[$property])) { return $this->data[$this::$_propertyList[$property]]; // 根据PHP属性名直接访问字段 } else { return $this->$property; // 如果没有对应的属性,则显示PHP默认的错误信息 } } function __set($property, $value) { if (isset($this::$_propertyList[$property])) { $field = $this::$_propertyList[$property]; $this->data[$field] = $value; // 更新$_data[字段名]的值 // 记录更新了的字段 if (!in_array($field, $this->changedFields)) { array_push($this->changedFields, $field); } } else { $this->data[$property] = $value; // 将不存在的属性全部统一存入$_data } } public function delete() { } public function insert() { global $dbh; if (empty($this->changedFields)) { $stmt = $dbh->prepare('INSERT INTO ' . $this::$_table['name'] . ' VALUES ()'); $rs = $stmt->execute(); } else { $fields = join(', ', $this->changedFields); $placeholders = str_repeat('?, ', count($this->changedFields) - 1) . '?'; $sql = 'INSERT INTO ' . $this::$_table['name'] . " ($fields) VALUES ($placeholders)"; $stmt = $dbh->prepare($sql); $param = 1; foreach ($this->changedFields as $field) { $stmt->bindValue($param++, $this->data[$field]); } $rs = $stmt->execute(); } if ($rs) { $this->changedFields = array(); // 获取生成的主键字段 if (is_string($this::$_table['key'])) { $this::$_table['key'] = array($this::$_table['key']); } $sql = 'SELECT ' . join(', ', $this::$_table['key']) . ' FROM ' . $this::$_table['name']; } return $rs; } public function update() { global $dbh; if (empty($this->changedFields) || empty($this::$_table['key'])) { return false; } // 禁止直接更新主键字段,如果必须要更新主键字段,请手动执行SQL语句 if (is_string($this::$_table['key'])) { $this::$_table['key'] = array($this::$_table['key']); } if (array_intersect($this->changedFields, $this::$_table['key'])) { trigger_error("Forbidden to update the primary key of a row", E_USER_WARNING); return false; } $sql = 'UPDATE ' . $this::$_table['name'] . ' SET '; $sql .= join(' = ?, ', $this->changedFields) . ' = ? WHERE '; $sql .= join(' = ? AND ', $this::$_table['key']) . ' = ?'; $stmt = $dbh->prepare($sql); $param = 1; foreach ($this->changedFields as $field) { $stmt->bindValue($param++, $this->data[$field]); } foreach ($this::$_table['key'] as $key) { $stmt->bindValue($param++, $this->data[$key]); } $rs = $stmt->execute(); if ($rs) { $this->changedFields = array(); // 若成功就清空字段列表 } return $rs; } }
// 相册类 class Album extends DataObject { protected static $_table = array('name' => 'Albums', 'key' => 'AlbumID'); // 设置PHP类对应的数据表的名称,以及数据表里所有主键的字段名称 protected static $_propertyList = array('id' => 'AlbumID', 'artist' => 'AlbumArtist', 'title' => 'AlbumTitle'); // PHP类属性名与数据表字段名的对应关系 // 获取前$num个相册对象的静态方法 public static function GetSomeAlbums($num) { global $dbh; // 调用外部变量$dbh $arr = array(); $sql = "SELECT * FROM Albums WHERE AlbumID <= $num"; $stmt = $dbh->query($sql); while ($album = $stmt->fetchObject('Album')) { $arr[] = $album; } return $arr; } // 获取指定标题的相册的静态方法 // 成功时返回Album对象,失败时返回NULL public static function GetAlbumByTitle($title) { global $dbh; $sql = "SELECT * FROM Albums WHERE AlbumTitle = ?"; $stmt = $dbh->prepare($sql); $stmt->bindValue(1, $title); $stmt->execute(); return $stmt->fetchObject('Album'); } }
$dbh = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'test', DB_PASSWORD);
$some = Album::GetSomeAlbums(6); // 获取前6个相册 echo 'Num: ', count($some), '<br>'; echo $some[1]->title, '<br>'; // ->title被魔术方法_get自动重定向到->data['AlbumTitle'] echo $some[2]->artist, '<br>'; // ->artist被魔术方法_get自动重定向到->data['AlbumArtist']
// 请不要直接通过DataObject更新主键字段 $some[1]->id = 100; $some[1]->update(); // 若要更新主键字段,请手动执行SQL语句 // 因为DataObject在更新记录时依赖于主键字段 $sql = 'UPDATE Albums SET AlbumID = 100 WHERE AlbumID = ' . $some[2]->id; //echo $sql, '<br>';
// 获取指定标题的相册 $dream = Album::GetAlbumByTitle('In My Dreams'); echo '<br>', $dream->artist, '<br>'; $abc = Album::GetAlbumByTitle('abc'); // 获取一个不存在的相册 if (!$abc) { echo 'No such album!!!<br>'; }
// 添加一个相册 /*$album = new Album(); $album->title = 'test title'; // 基类DataObject会自动记录更新了哪些字段 $album->artist = 'test artist'; if ($album->insert()) { printf('Inserted! ID = %d<br>', $album->id); }*/
/* // 添加空白相册记录 $album = new Album(); $album->insert(); */
/*$stmt = $dbh->query('SELECT * FROM Albums WHERE AlbumID = 6'); $album = $stmt->fetchObject('Album'); // 所有的数据都会自动存入data数组中 if ($album) { print_r($album); // 输出$album对象的结构 echo '<br><b>Title: </b>'; echo $album->title; // 更新字段 if ($album->title != 'New Title') { $album->title = 'New Title'; if ($album->update($dbh)) { echo '<p>Updated</p>'; } } } else { // 记录不存在 echo 'No such record!'; }*/ ?>
|