数据映射模式
<ul>
<li>将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作。</li>
</ul>
<h3>深入理解数据映射</h3>
<ul>
<li>是在持久化数据存储层(一般是关系型数据库)和驻于内存的数据表现层之间进行双向数据传输的数据访问层。</li>
</ul>
<h3>目的</h3>
<ul>
<li>是让持久化数据存储层,驻于内存的数据表现层,以及数据映射本身三者相互独立、互不依赖。</li>
<li>数据访问层由一个映射器(或者数据访问对象)组成,用于实现数据传输。</li>
<li>通用的数据访问层可以处理不同的实体类型,而专用的则处理一个或几个。</li>
</ul>
<h3>数据映射模式的核心</h3>
<ul>
<li>在于它的数据模型遵循单一职责原则(single Responsibility Principle),这也是和Active Record模式的不同之处。</li>
<li>最典型的数据映射模式例子就是数据库ORM模型(Object Relational Mapper)。</li>
</ul>
<h2>代码示例</h2>
<pre><code class="language-PHP"><?php
/**
* 数据库 test 编码 utf8mb4
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL DEFAULT '' COMMENT '姓名',
`tel` char(11) NOT NULL DEFAULT '' COMMENT '手机号',
`create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='用户';
*/
interface IDatabase
{
function connect($host, $user, $passwd, $dbname);
function query($sql);
function close();
}
class User
{
public $id, $name, $tel, $create_time;
protected $db;
function __construct($id)
{
$this->db = new mysqli();
$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';
</code></pre>