数据映射模式


// 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';

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