/** * 数据对象映射莫使,就是将对象和数据存储映射起来,对一个对象的操作就是对数据库的操作 */ interface Database{ public function connect($host, $name, $password, $db); public function query($sql); public function close(); } class MYSQLI implements Database{ protected $conn; public function connect($host, $name, $password, $db) { $this->conn = mysqli_connect($host, $name, $password, $db); } public function query($sql) { return mysqli_query($this->conn,$sql); } public function close() { mysqli_close($this->conn); } } class User{ protected $data; protected $db; public function __construct($id){ $this->db = new MYSQLI('127.0.0.1','admin','admin','oo'); $res = $this->db->query('select * from user where id = '.$id); $this->data = $res->fetch_assoc(); } protected function __set($key,$value){ $this->data[$key] = $value; } protected function __get($key){ $this->$key = $this->data[$key]; } public function save(){ $key = array_keys($this->data); $value = array_values($this->data); $sql = 'update user set () '.$key.' values '.$value.' where id = '.$this->id; if($this->db->query($sql)){ echo 'ok'; } } protected function __destruct(){ $this->db->close(); } }
php 设计模式(数据库对象模式)
最新推荐文章于 2022-02-07 14:42:07 发布