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

設計模式之資料對映模式

資料對映模式其實用過laravel框架的話已經接觸過了,laravel中的ORM就是用的資料對映模式
class Mysqli{
	private $conn;
	function connect($host, $user, $pass, $dbname){
		$conn = mysqli_connect($host, $user, $pass, $dbname);
		mysqli_query($conn, "set names utf8");
		$this->conn = $conn;
	}

	function query($sql){
		$res = mysqli_query($this->conn, $sql);
		return $res;
	}

	function close(){
		mysqli_close($this->conn);
	}
}
首先建立一個Mysqli的類,方便之後呼叫。
class User{
	public $id;
	public $name;
	public $age;
	public $nickname;

	protected $db;

	function __construct($id){
		$this->db = new Mysqli();
		$this->db->connect('127.0.0.1', 'root', '', 'test');
		$res = $this->db->query("select * from user where id=$id");
		$data = $res->fetch_assoc();

		$this->id = $id;
		$this->name = $data['name'];
		$this->age = $data['age'];
		$this->nickname = $data['nickname'];
	}

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

User表的結構如下


然後我們對User進行操作
$user = new Tool\User(1);
$user->name = 'Lee';
$user->age = '23';
$user->nickname = '大毛';
執行完後結果如圖


當然ORM肯定不止那麼簡單,還需要後續的深入學習