您的位置:首页 > 编程语言 > PHP开发

PHP设计模式之数据对象映射模式

2016-11-19 00:00 567 查看
数据映射模式使您能更好的组织你的应用程序与数据库进行交互。

数据映射模式将对象的属性与存储它们的表字段间的结合密度降低。数据映射模式的本质就是一个类,它映射或是翻译类的属性或是方法到数据库的相应字段,反之亦然。

数据映射的作用(工作)就在于能对双方所呈现出的信息的理解,并能对信息的存取进行控制,如根据存储在数据表中的信息,重建新的域对象,或是用域对象的信息来更新或删除数据表中的相关数据。

对于面向对象代码与数据库表和字段间的映射关系的存储有多种实现方式。其中一种可能的方法就通过手工编码将这种映射关系存储在数据映射类中。

另一种可选的方法是用PHP的数组并将其编码为类本身。这个类也能外源获取数据,如INI或是XML文件。

数据对象映射模式,是将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作。

User.php
<?php
class User
{
protected $id;
protected $data;
protected $db;
protected $change = false;
function __construct($id)
{
$this->db = Factory::getDatabase();
$res = $this->db->query("select * from user where id = $id limit 1");
$this->data = $res->fetch_assoc();
$this->id = $id;
}
function __get($key)
{
if (isset($this->data[$key]))
{
return $this->data[$key];
}
}
function __set($key, $value)
{
$this->data[$key] = $value;
$this->change = true;
}
function __destruct()
{
if ($this->change)
{
foreach ($this->data as $k => $v)
{
$fields[] = "$k = '{$v}'";
}
$this->db->query("update user set " . implode(', ', $fields) . "where
id = {$this->id} limit 1");
}
}
}

Factory.php
<?php
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;
}
}

index.php
$db=new User(1);
$db->title='fdf';
$db->gtitle='gfdds';

<?php
class Register
{
protected static $objects;

static function set($alias, $object)
{
self::$objects[$alias] = $object;
}

static function get($key)
{
if (!isset(self::$objects[$key]))
{
return false;
}
return self::$objects[$key];
}

function _unset($alias)
{
unset(self::$objects[$alias]);
}
}


注意: 可以用魔术方法__get __set, 来实时获取和修改某个用户的属性
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息