课程名称:大话PHP设计模式
课程章节: 8-1数据对象映射模式之简单案例实现、8-2数据对象映射模式之复杂案例实现
课程链接
主讲老师:Rango
课程内容
叙述了数据对象模式的定义,首先通过简单的案例代码,来让我们对这种模式有个初步的理解。然后通过复杂案例的描述,加深我们对这种模式的理解,让我们能够使用到日常代码中。
课程收获
数据对象映射模式
1、数据对象映射模式,是将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作
2、在代码中实现数据对象映射模式,我们将实现一个ORM类,将复杂的SQL语句,映射成对象属性的操作
3、结合使用数据对象映射模式、工厂模式、注册模式
简单案例实现
class User
{
public $id;
public $name;
public $mobile;
public $regtime;
protected $db;
function __construct()
{
$this->db = new Database\MySQLi;
$res = $this->db->connect('127.0.0.1','root','root','test');
$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("updata user set name = '{$this->name}',mobile = '{$this->mobile}',regtime = '{$this->regtime}' where id = '{$this->id}'");
}
}
$user = new User;
$user->name = 'LDR_1109';
$user->mobile = '13298654268';
$user->regtime = date('Y-m-d H:i:s');
复杂案例实现
class User
{
public $id;
public $name;
public $mobile;
public $regtime;
protected $db;
function __construct()
{
$this->db = new Database\MySQLi;
$res = $this->db->connect('127.0.0.1','root','root','test');
$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("updata user set name = '{$this->name}',mobile = '{$this->mobile}',regtime = '{$this->regtime}' where id = '{$this->id}'");
}
}
class Factory
{
static function createDatabase()
{
$db = Database::getInstance();
Register::set('test',$db);
return $db;
}
static function getUser($id)
{
$key = 'user_'.$id;
$user = Register::get($key);
if(!$user) {
$user = new User($id);
Register::set($key,$user);
}
return $user;
}
}
class Page
{
function index()
{
$user = Factory::getUser(1);
$user->name = 'Rango';
$user->test();
echo "OK";
}
function test()
{
$user = Factory::getUser(1);
$user->mobile = '18845424156';
}
}
$user = new Page;
$user->index();