PHP数据对象映射模式
Posted by 撒得一地 on 2016年2月21日 in PHP笔记
数据对象映射模式,是将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作。比如在代码中生成一个对象,使用数据对象映射模式就可以将生成对象中的一些操作结果或者属性自动保存到数据库中。数据对象映射模式通常和数据库数据存储相结合。
下面在代码中实现数据对象映射模式,我们将实现一个ORM类,将复杂的SQL语句映射成对象属性的操作。
首先假设数据库中已经存在了一张表,表名为user,字段分别为id,name,tel,create_time。创建表的sql语句为:
create table user( `id` int primary key auto_increment, `name` varchar(20), `tel` varchar(11), `create_time` int(11) );
//定义关于数据库的类
interface IDatabase
{
function connect($host,$user,$passwd,$dbname);
function query($sql);
function close();
}
//下面定义一个用mysql操作数据库的类
class Mysql implements IDatabase
{
protected $conn;
function connect($host,$user,$passwd,$dbname)
{
$conn = mysql_connect($host,$user,$passwd);
mysql_select_db($dbname,$conn);
$this->conn = $conn;
}
function query($sql)
{
$res = mysql_query($sql,$this->conn);
return $res;
}
function close()
{
mysql_close($this->conn);
}
}
//定义一个用户表
class User{
public $id,$name,$tel,$create_time;
protected $db;
function __construct($id){
$this->db = new mysql();
$this->db->connect('127.0.0.1','root','root','test');
$res = $this->db->query("select * from `user` where `id` = $id limit 1");
$data = $res->fetch_assoc();
$this->id = $data['id'];
$this->name = $data['name'];
$this->tel = $data['tel'];
$this->create_time = $data['create_time '];
}
function __destruct(){
$this->db->query("update user set name = '{$this->name}',tel = '{$this->tel}', create_time={$this->create_time} where id={$this->id}");
}
}
//这样主函数中直接实现数据对象映射 $user = new User(1); $user->name = 'psz'; $user->create_time = time(); $user->tel = '1880xxxxxx1';
上面这样操作的好处是,主函数中直接操作属性或数据,然后直接将数据映射到相关的数据表中。这样写的好处是将底层数据库操作隐藏,简洁了主函数代码。这种操作在框架中尤为常见,大大方便了使用者对数据库的操作。