是将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作。
例如在代码中 new 一个对象,使用数据对象映射模式就可以将对象的一些操作比如设置一些属性,就会自动保存到数据库,跟数据库中表的一条记录对应起来。

<?php

namespace Lib;

class User
{
    public $id;
    public $name;
    public $email;
    public $addtime;

    private $db;

    public function __construct($id)
    {
        $this->db = Factory::getDb();
        $this->db->connect('127.0.0.1','root',123456,'demo');
        $result = $this->db->query("select * from user where id = $id");
        $row = $result->fetch_assoc();
        $this->id = $row['id'];
        $this->name = $row['name'];
        $this->email = $row['email'];
        $this->addtime = $row['addtime'];
    }

    public function __destruct()
    {
        $this->db->query("update user set name = '{$this->name}',email = '{$this->email}',addtime = '{$this->addtime}' where id = '{$this->id}'");
    }
}
public static function getUser($id)
{
    $key = 'user'.$id;
    $user = Register::get($key);
    if(!$user)
    {
        $user = new \Lib\User($id);
        Register::set($key,$user);
    }
    return $user;
}
$user = \Lib\Factory::getUser(1);
print_r($user);

results matching ""

    No results matching ""

    results matching ""

      No results matching ""