數據對象映射模式,是將對象和數據存儲映射起來,對一個對象的操作會映射為對數據存儲的操作。
在代碼中實現數據對象映射模式,實現一個ORM類,將復雜的sql語句映射成對象屬性的操作。對象關系映射(Object Relational Mapping,ORM)
ha_cl表
Hacl.php
<?php
namespace Baobab;
class Hacl{
public $id;
public $haclname;
public $haclcode;
public $hacls;
protected $db;
function __construct($id){
$this->db = new \Baobab\Database\Mysqli();
$this->db->connect('127.0.0.1', 'root', '', 'test');
$res = $this->db->query("select * from ha_cl where id = {$id}");
$data = $res->fetch_assoc();
$this->id = $data['ID'];
$this->haclname = $data['ha_cl_name'];
$this->haclcode = $data['ha_cl_code'];
$this->hacls = $data['hacls'];
}
function __destruct(){
$this->db->query("update ha_cl set
ha_cl_code = '{$this->haclcode}',
ha_cl_name = '{$this->haclname}',
hacls = '{$this->hacls}'
where ID = {$this->id}
limit 1");
}
}
Factory.php
<?php
namespace Baobab;
class Factory{
static function getHacl($id){
$key = 'user_'.$id;
$user = \Baobab\Register::get($key);//表中id不同表示的是不同的對象
if(!$user){
$user = new \Baobab\Hacl($id);
\Baobab\Register::set($key, $user);
}
return $user;
}
}
Register.php
<?php
namespace Baobab;
class Register{
protected static $objects;
static function set($alias, $object){
self::$objects[$alias] = $object;
}
static function _unset($alias) {
unset(self::$objects[$alias]);
}
static function get($name) {
return self::$objects[$name];
}
}
index.php
class Page{
function index(){
$hacl = Baobab\Factory::getHacl(13);
$hacl->haclname = '測試名稱';
$this->test();
echo 'ok';
}
function test(){
$hacl = Baobab\Factory::getHacl(13);
$hacl->hacls = '測試內容';
}
}
$page = new Page();
$page->index();
使用工廠模式會多次創建對象Hacl,浪費資源,如果將對象作為參數傳遞,一方面會帶來額外的使用成本,另外如果很多地方都用到這個對象很容易發生錯誤,因此在工廠模式中使用注冊樹模式來解決這個問題。