PHP設計模式(4)—— 資料物件對映模式
阿新 • • 發佈:2018-12-01
基本概念
資料物件對映模式,是將物件和資料儲存對映起來,對一個物件操作會對映成對資料儲存的操作。
這個模式的應用例子就是現在流行的ORM。
簡單例子
User類
class User
{
// 屬性和資料庫表的欄位一一對應
public $id;
public $name;
public $mobile;
public $regtime;
// 資料庫物件
protected $db;
// 建構函式
function __construct($id){
// 連線資料庫、查詢資料
$this->db = new PDO ("mysql:host=localhost; dbname=test",'root','');
// 查詢
$sql = "SELECT * FROM user where id = " . $id . " LIMIT 1";
$stmt = $this->db->query($sql);
// 獲取結果集
$data = $stmt -> fetch(PDO::FETCH_ASSOC);
/******************* 屬性賦值 ************************/
$this->id = $data['id'] ;
$this->name = $data['name'];
$this->mobile = $data['mobile'];
$this->regtime = $data['regtime'];
}
// 解構函式
function __destruct(){
// 更新資料
$sql = "UPDATE user SET name = '{$this->name}' WHERE id = {$this->id} LIMIT 1";
$this->db->exec($sql);
}
}
使用User類
$user = new User(1);
// 修改屬性
$user->name = 'tim';