ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 8-1 数据对象映射模式之简单案例实现 ### 1. 创建`user`表 ~~~ -- 创建用户表 CREATE TABLE IF NOT EXISTS `user`( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(30) NOT NULL DEFAULT '', `passwd` VARCHAR(32) NOT NULL DEFAULT 'e10adc3949ba59abbe56e057f20f883e', `created_time` INT(10) NOT NULL DEFAULT 0 )ENGINE=InnoDB DEFAULT CHARSET=UTF8; -- 测试数据 INSERT INTO `user` (name, passwd, created_time) VALUES ('Mark', md5('12345'), UNIX_TIMESTAMP()), ('Lily', md5('12345'), UNIX_TIMESTAMP()), ('Lucy', md5('12345'), UNIX_TIMESTAMP()), ('Bob', md5('12345'), UNIX_TIMESTAMP()), ('Tom', md5('12345'), UNIX_TIMESTAMP()), ('Christian', md5('12345'), UNIX_TIMESTAMP()); ~~~ ### 2. 创建`User`类 *D:\wamp\www\demo\oop\framework\Think\User.php* ~~~ <?php namespace Think; class User { public $id; public $name; public $passwd; public $created_time; function __construct($id) { // 创建对象后,自动执行 } function __destruct() { // 对象注销前,自动执行 } } ~~~ ### 3. 使用构造方法实现数据的读取操作 *D:\wamp\www\demo\oop\framework\Think\User.php* ~~~ <?php namespace Think; class User { public $id; public $name; public $passwd; public $created_time; protected $db; function __construct($id) { // 创建对象后,自动执行 $this->db = new Database\MySQLi(); $this->db->connect('localhost', 'root', 'root', 'demo'); $ret = $this->db->query('SELECT * FROM `user` WHERE `id` = ' . $id); $this->db->close(); $data = mysqli_fetch_assoc($ret); $this->id = $data['id']; $this->name = $data['name']; $this->passwd = $data['passwd']; $this->created_time = $data['created_time']; } function __destruct() { // 对象注销前,自动执行 } } ~~~ ### 4. 在入口文件处,获取数据表中的值 *D:\wamp\www\demo\oop\framework\index.php* ~~~ // 实例化1个用户表对象:User $user = new Think\User(2); // 获取对象中的属性,对象数据表中的一条记录 echo $user->id."<br/>"; echo $user->name."<br/>"; echo $user->passwd."<br/>"; echo $user->created_time."<br/>"; ~~~ ### 5. 使用析构方法自动保存数据 *D:\wamp\www\demo\oop\framework\index.php* ~~~ // 修改属性值之后,利用析构方法自动保存 $user->name = '王五'; $user->passwd = md5('123'); $user->created_time = time(); ~~~ *D:\wamp\www\demo\oop\framework\Think\User.php* ~~~ function __destruct() { // 对象注销前,自动执行 $sql = "UPDATE `user` SET name = '{$this->name}', passwd = '{$this->passwd}', created_time = '{$this->created_time}' WHERE id = {$this->id}"; echo $sql; $this->db->query($sql); $this->db->close(); } ~~~