PHP设计模式(4)—— 数据对象映射模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lihaoen666/article/details/84646186

基本概念

数据对象映射模式,是将对象和数据存储映射起来,对一个对象操作会映射成对数据存储的操作。

这个模式的应用例子就是现在流行的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';

猜你喜欢

转载自blog.csdn.net/lihaoen666/article/details/84646186
今日推荐