概念:简言之,数据映射模式就是将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作。
深入理解:数据映射,是在持久化数据存储层(一般是关系型数据库)和驻于内存的数据表现层之间进行双向数据传输的数据访问层。
数据映射模式的目的是让持久化数据存储层,驻于内存的数据表现层,以及数据映射本身三者相互独立、互不依赖。这个数据访问层由一个映射器(或者数据访问对象)组成,用于实现数据传输。通用的数据访问层可以处理不同的实体类型,而专用的则处理一个或几个。
数据映射模式的核心在于它的数据模型遵循单一职责原则(single Responsibility Principle),这也是和Active Record模式的不同之处。最典型的数据映射模式例子就是数据库ORM模型(Object Relational Mapper)。
代码演示:
1.表结构
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(32) | NO | | | |
| mobile | int(11) | NO | | 0 | |
| regtime | timestamp | YES | | NULL | |
+---------+------------------+------+-----+---------+----------------+
2.代码结构
LibsIDatabase.php
<?php namespace Libs; interface IDatabase { function connect($host,$user,$pwd,$dbname); function query($sql); function close(); }
LibsDatabaseMySQLi.php
<?php namespace LibsDatabase; use LibsIDatabase; class MySQLi implements IDatabase { protected $conn; public function connect($host,$user,$pwd,$dbname) { $conn = mysqli_connect($host,$user,$pwd,$dbname); $this->conn = $conn; } public function query($sql) { $res = mysqli_query($this->conn,$sql); return $res; } public function close() { mysqli_close($this->conn); } }
LibsFactory.php
<?php namespace Libs; class Factory { public static function getUser($id) { $key = 'user_'.$id; $user = Register::get($key); if(!$user){ $user = new User($id); Register::set($key, $user); } return $user; } }
LibsUser.php
<?php namespace Libs; class User { public $id; public $name; public $mobile; public $regtime; protected $db; public function __construct($id) { $this->db = new LibsDatabaseMySQLi(); $this->db->connect(DBHOST, DBUSER, DBPWD, DBNAME); $res = $this->db->query("SELECT * FROM user WHERE id={$id} LIMIT 1"); $data = $res->fetch_assoc(); $this->id= $id; $this->mobile = $data['mobile']; $this->name = $data['name']; $this->regtime = $data['regtime']; } public function __destruct() { $this->db->query("update user set name='{$this->name}',mobile='{$this->mobile}',regtime='{$this->regtime}' where id={$this->id} limit 1"); } }
LibsUserMapper.php
<?php namespace Libs; class UserMapper { public function index($id) { $user = LibsFactory::getUser($id); $user->mobile = "1891111111"; $this->changeName($id); echo "done"; } public function changeName($id) { $user = LibsFactory::getUser($id); $user->name = "sacha"; } }
调用
define("DBHOST",'127.0.0.1'); define("DBUSER",'user'); define("DBPWD",'pwd'); define("DBNAME",'test'); $um = new LibsUserMapper(); $um->index(1);
推荐阅读:
Eloquent ORM 实例教程 —— ORM概述、模型定义及基本查询