PHP设计模式之数据对象映射模式

  1. 数据对象映射模式,是将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作
  2. 在代码中实现数据对象映射模式,我们将实现一个ORM类,将复杂的SQL语句映射成对象属性操作。

demo1.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
header('Content-Type:text/html; charset=utf-8');

class DB{
private $pdo;

public function __construct(){
try{
$drive_opt = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
$this->pdo = new PDO('mysql:host=localhost;dbname=db', 'root', 'password', $drive_opt);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
exit('数据库连接错误:'.$e->getMessage());
}
}

public function query($sql){
return $this->pdo->query($sql);
}
};

class User{
public $id;
public $name;
public $email;
private $db;

public function __construct($id){
$this->db = new DB();
$res = $this->db->query('select * from user limit 1 where id='.$id);
$data = $res->fetch_assoc();
$this->id = $id;
$this->name = $data['name'];
$this->email = $data['email'];
}

public function save(){
$this->db->query("update user set name='$this->name', email='$this->email' where id=$this->id");
}
}

$user = new User(1);
var_dump($user);
$user->name = 'suse';
$user->email = 'suse@iphpjs.com';
$user->save();