关于php:php设计模式五数据对象映射模式-orm

5次阅读

共计 621 个字符,预计需要花费 2 分钟才能阅读完成。

数据对象映射模式 orm

  1. 对象和数据存储映射,对对象的操作映射为对数据的存储操作
// 映射到 user 表
class User {
    public $id;
    public $name;
    public $regtime;
    
    private $db;
    public function __counstruct($id){$this->db = (new Factory())->createDB);
        $this->db->connect($host,$user,$pwd,$dbname);  // 这里为工厂模式创立,能够改为这册器模式,进一步进行优化,例如一次业务中须要实例化这个类屡次。这里不能用单利模式,因为每个 id 应该为不同的实例
        $rlt = $this->db->query("select * from user where id ='$id'")->fetchAll();
        
        // 建设映射关系
        $this->id = $rlt['id'];
        $this->name = $rlt['name'];
        $this->regtime = $rlt['regtime'];
    }
    
    
    public function __destruct(){$this->db->exec("update user set name = $this->name regtime=$this->regtime where id = $id");
    }
}

$user = new User(1); // 操作 id 为 1 的用户
$user->name="aa";
$user->regtiem = time();
正文完
 0