數據映射模式

<?php
// php 技術羣:781742505

// 就是 ORM。在數據對象層和業務層中間加上映射層。
//
// CREATE TABLE `user` (
// `id` int(11) NOT NULL AUTO_INCREMENT,
//	  `name` varchar(32) CHARACTER SET utf8 DEFAULT NULL,
//	  `mobile` varchar(11) CHARACTER SET utf8 DEFAULT NULL,
//	  `regtime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
//	  PRIMARY KEY (`id`)
// ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARSET = latin1;

/**
 * Class User
 */
class User
{
    /**
     * @var
     */
    public $id;
    /**
     * @var
     */
    public $name;
    /**
     * @var
     */
    public $mobile;
    /**
     * @var MySQLi
     */
    protected $db;

    //構造方法

    /**
     * User constructor.
     *
     * @param $id
     */
    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} limit 1");
        $data = $res->fetch_assoc();
        $this->id = $data['id'];
        $this->name = $data['name'];
        $this->mobile = $data['mobile'];
    }

    //析構方法

    /**
     *
     */
    function __destruct()
    {
        $this->db->query("update user set name = '{$this->name}', mobile = '{$this->mobile}' where id = {$this->id} limit 1");
    }
}

/**
 * Class MySQLi
 */
class MySQLi
{
    /**
     * @var
     */
    protected $conn;

    /**
     * @param $host
     * @param $user
     * @param $passwd
     * @param $dbname
     */
    function connect($host, $user, $passwd, $dbname)
    {
        $conn = mysqli_connect($host, $user, $passwd, $dbname);
        $this->conn = $conn;
    }

    /**
     * @param $sql
     *
     * @return bool|mysqli_result
     */
    function query($sql)
    {
        $res = mysqli_query($this->conn, $sql);

        return $res;
    }

    /**
     *
     */
    function close()
    {
        mysqli_close($this->conn);
    }
}

$user = new User(1);
$user->name = 'Lee';
$user->mobile = '12345678901';

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章