数据对象映射模式
定义:将对象和数据存储映射起来,对一个对象的操作会映射为数据存储的操作
综合应用实例:在代码中实现数据对象映射模式,我们将实现一个ORM类,将复杂的SQL语句映射成对象属性的操作,结合使用数据对象映射模式,工程模式,注册模式
$page = new Page();
$page->index();
class Page
{
function index()
{
$user = \IMooc\Factory::getUser(1);
$user->name= 'fango0';
$this->test();
}
function test()
{
$user = \IMooc\Factory::getUser(1);
$user->moblie = '19123230';
}
}<?php
namespace IMooc;
class User
{
public $id;
public $name;
public $moblie;
public $regtime;
protected $db;
function __construct($id)
{
$this->db = new \IMooc\Database\MySQLi();
$this->db->connect('127.0.0.1', 'root', 'root', 'test');
$res = $this->db->query("select * from user limit 1");
$data = $res->fetch_assoc();
$this->id = $data['id'];
$this->name = $data['name'];
$this->mobile = $data['mobile'];
$this->regtime = $data['regtime'];
}
function __destruct()
{
$this->db->query("update user set name = '{$this->name}',mobile='{$this->moblie}',regtime='{$this->regtime}' WHERE id={$this->id}");
}
}<?php
namespace IMooc;
class Factory
{
static function getUser($id)
{
$key = 'user_'.$id;
$user = Register::get($key);
if (!$user)
{
$user = new User($id);
Register::set($key, $user);
}
return $user;
}
}<?php
namespace IMooc;
class Register
{
protected static $objects;
static function set($alias, $object)
{
self::$objects[$alias] = $object;
}
static function get($alias)
{
return self::$objects[$alias];
}
function _unset($alias)
{
unset(self::$objects[$alias]);
}
}
只言片语任我说,提笔句句无需忖。落笔不知寄何人,唯有邀友共斟酌。