码迷,mamicode.com
首页 > 其他好文 > 详细

数据对象映射模式

时间:2016-12-24 22:56:00      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:data   php   复杂   roo   page   this   pac   dex   objects   

定义:将对象和数据存储映射起来,对一个对象的操作会映射为数据存储的操作
综合应用实例:在代码中实现数据对象映射模式,我们将实现一个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]);
}
}






数据对象映射模式

标签:data   php   复杂   roo   page   this   pac   dex   objects   

原文地址:http://www.cnblogs.com/phonecom/p/b87453bd8d162c70655462eba7178f76.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!