1. 程式人生 > >php設計模式 --- 資料對映模式

php設計模式 --- 資料對映模式

1、模式定義

在瞭解資料對映模式之前,先了解下資料對映,它是在持久化資料儲存層(通常是關係型資料庫)和駐於記憶體的資料表現層之間進行雙向資料傳輸的資料訪問層。

資料對映模式的目的是讓持久化資料儲存層、駐於記憶體的資料表現層、以及資料對映本身三者相互獨立、互不依賴。這個資料訪問層由一個或多個對映器(或者資料訪問物件)組成,用於實現資料傳輸。通用的資料訪問層可以處理不同的實體型別,而專用的則處理一個或幾個。

資料對映模式的核心在於它的資料模型遵循單一職責原則(Single Responsibility Principle), 這也是和 Active Record 模式的不同之處。最典型的資料對映模式例子就是資料庫 ORM 模型 (Object Relational Mapper)。

:將物件和資料儲存對映起來,對一個物件的操作會對映為對資料儲存的操作。例如在程式碼中 new 一個物件,使用資料物件對映模式就可以將物件的一些操作比如設定一些屬性,就會自動儲存到資料庫,跟資料庫中表的一條記錄對應起來。

【例1】

user 表結構:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) CHARACTER SET utf8 DEFAULT NULL,
  `mobile` varchar(11) CHARACTER SET utf8 DEFAULT NULL,
  `regtime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE
=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

Common\User.php:

<?php
namespace Common;

class User{
    public $id;
    public $name;
    public $mobile;
    public $regtime;
    
    protected $db;

    //構造方法
    function __construct($id) {
        $this->db = new Database\MySQLi();
        $conn 
= $this->db->connect('127.0.0.1', '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->mobile = $data['mobile']; $this->regtime = $data['regtime']; } //析構方法 function __destruct() { $this->db->query("update user set name = '{$this->name}', mobile = '{$this->mobile}', regtime = '{$this->regtime}' where id = {$this->id} limit 1"); } }

Common\Databases\MySQLi.php

<?php
namespace Common\Database;
use Common\IDatabase;

class MySQLi implements IDatabase{
    
    protected $conn;
    function connect($host, $user, $passwd, $dbname){
        $conn = mysqli_connect($host, $user, $passwd ,$dbname);
        $this->conn = $conn;
    }
    
    function query($sql){
        $res = mysqli_query($this->conn, $sql);
        return $res;
    }

    function close(){
        mysqli_close($this->conn);
    }
}

入口檔案 index.php

<?php
 2 define('BASEDIR',__DIR__); //定義根目錄常量
 3 include BASEDIR.'/Common/Loader.php';
 4 spl_autoload_register('\\Common\\Loader::autoload');
 5 echo '<meta http-equiv="content-type" content="text/html;charset=utf8">';
 6 
 7 /*
 8  * 對物件屬性的操作就完成了對資料庫的操作
 9  */
10 $user = new Common\User(1);
11 
12 //讀取資料
13 var_dump($user->id, $user->mobile, $user->name, $user->regtime);exit();
14 
15 $user->mobile = '13800138000';
16 $user->name = 'Arshavin';
17 $user->regtime = date("Y-m-d H:i:s",time());

line 13 輸出(原始表中的資料):

string '1' (length=1)
string '10086' (length=5)
string 'K6' (length=2)
string '2015-05-07 00:16:12' (length=19)

註釋 line 13,訪問入口檔案,則資料庫的資料被修改