设计模式之数据映射模式

数据映射模式其实用过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肯定不止那么简单,还需要后续的深入学习

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