数据对象映射模式

概念与目的

概念: 描述如何创建提供透明访问任何数据源的对象。数据映射模式,也叫数据访问对象模式,或数据对象映射模式。

目的: 数据映射模式的目的是让持久化数据存储层、驻于内存的数据表现层、以及数据映射本身三者相互独立、互不依赖

简单例子–数据库ORM模型(Object Relational Mapper)

database.php
mysqli.php


/**
 * Created by PhpStorm.
 * User: 何晓宏
 * Date: 2018/9/30
 * Time: 0:42
 */
namespace Dataobjectmapperpattern;
interface Database{
    function connect($host, $user, $passwd, $db);
    function query($sql);
    function close();
}


/**
 * Created by PhpStorm.
 * User: 何晓宏
 * Date: 2018/9/30
 * Time: 0:42
 */
namespace Dataobjectmapperpattern;
class MySQLi implements Database{

    protected $conn;
    function connect($host, $user, $passwd, $db)
    {
        $conn=mysqli_connect($host, $user, $passwd, $db);
        $this->conn=$conn;
    }
    function query($sql)
    {
        return mysqli_query($this->conn,$sql);
    }
    function close()
    {
        mysqli_close($this->conn);
    }
}

user.php


/**
 * Created by IntelliJ IDEA.
 * User: 何晓宏
 * Date: 2018/10/10
 * Time: 15:25
 */
namespace Dataobjectmapperpattern;
class User{
    public $id;
    public $name;
    public $password;

    protected $db;

    function __construct($id)
    {
        $this->db=new MySQLi();
        $this->db->connect("127.0.0.1","root","password","test");
        $res=$this->db->query("select * from user limit 1");
        $data=$res->fetch_assoc();
        $this->id=$data['id'];
        $this->name=$data['name'];
        $this->password=$data['password'];

    }

    function __destruct()
    {
        $this->db->query("update user set name='{$this->name}',
                password='{$this->password}' where id='{$this->id}' limit 1");
    }

}
		$user=factory::getuser(1);
        //var_dump($user->id,$user->name,$user->password);
        //exit;
        $user->name='wxz';
        $user->password='123';

表结构

数据对象映射模式_第1张图片

优点

  • 遵循单一职责原则
  • 将持久化数据存储层,驻于内存的数据表现层,以及数据映射本身三者相互独立、互不依赖

你可能感兴趣的:(设计模式)