|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * 数据访问对象模式 |
| 4 | + * 解决问题:如何创建透明访问任何数据源的对象(重复和数据源抽象化) |
| 5 | + */ |
| 6 | + |
| 7 | +abstract class baseDAO |
| 8 | +{ |
| 9 | + private $__connection; |
| 10 | + public function __construct() |
| 11 | + { |
| 12 | + $this->__connectToDB(DB_USER, DB_PASS, DB_HOST, DB_DATABASE); |
| 13 | + } |
| 14 | + |
| 15 | + private function __connectToDB($user, $pass, $host, $database) |
| 16 | + { |
| 17 | + $this->__connection = mysql_connect($host, $user, $pass); |
| 18 | + mysql_select_db($database, $this->__connection); |
| 19 | + } |
| 20 | + |
| 21 | + public function fetch($value, $key = NULL) |
| 22 | + { |
| 23 | + if(is_null($key)) |
| 24 | + { |
| 25 | + $key = $this->_primaryKey; |
| 26 | + } |
| 27 | + |
| 28 | + $sql = "select * from {$this->_tableName} where {$key}='{$value}'"; |
| 29 | + $results = mysql_query($sql, $this->__connection); |
| 30 | + |
| 31 | + $rows = array(); |
| 32 | + while ($result = mysql_fetch_array($results)) |
| 33 | + { |
| 34 | + $rows[] = $result; |
| 35 | + } |
| 36 | + return $rows; |
| 37 | + } |
| 38 | + |
| 39 | + public function update($keyedArray) |
| 40 | + { |
| 41 | + $sql = "update {$this->_tableName} set "; |
| 42 | + foreach ($keyedArray as $column=>$value) |
| 43 | + { |
| 44 | + $updates[] = "{$column} = '{$value}' "; |
| 45 | + } |
| 46 | + $sql .= implode(",",$updates); |
| 47 | + $sql .= "where {$this->_primaryKey}='{$keyedArray[$this->_primaryKey]}'"; |
| 48 | + mysql_query($sql, $this->__connection); |
| 49 | + |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +class userDAO extends baseDAO |
| 54 | +{ |
| 55 | + protected $_tableName = "userTable"; |
| 56 | + protected $_primaryKey = "id"; |
| 57 | + |
| 58 | + public function getUserByFirstName($name) |
| 59 | + { |
| 60 | + $result = $this->fetch($name, 'firstName'); |
| 61 | + return $result; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | + |
| 66 | +$user = new userDAO(); |
| 67 | +$id = 1; |
| 68 | +$userInfo = $user->fetch($id); |
| 69 | + |
| 70 | +$updates = array('id'=>1, 'firstName'=>'arlon'); |
| 71 | +$user->update($updates); |
| 72 | + |
| 73 | +$all = $user->getUserByFirstName('arlon'); |
0 commit comments