php中的設(shè)計模式中有很多的各種模式了,在這里我們來為各位介紹一個不常用的數(shù)據(jù)映射模式吧,希望文章能夠幫助到各位。
數(shù)據(jù)映射模式使您能更好的組織你的應(yīng)用程序與數(shù)據(jù)庫進行交互。
數(shù)據(jù)映射模式將對象的屬性與存儲它們的表字段間的結(jié)合密度降低。數(shù)據(jù)映射模式的本質(zhì)就是一個類,它映射或是翻譯類的屬性或是方法到數(shù)據(jù)庫的相應(yīng)字段,反之亦然。
數(shù)據(jù)映射的作用(工作)就在于能對雙方所呈現(xiàn)出的信息的理解,并能對信息的存取進行控制,如根據(jù)存儲在數(shù)據(jù)表中的信息
重建新的域?qū)ο螅蚴怯糜驅(qū)ο蟮男畔砀禄騽h除數(shù)據(jù)表中的相關(guān)數(shù)據(jù)。
對于面向?qū)ο蟠a與數(shù)據(jù)庫表和字段間的映射關(guān)系的存儲有多種實現(xiàn)方式。其中一種可能的方法就通過手工編碼將這種映射關(guān)系存儲在數(shù)據(jù)映射類中。
另一種可選的方法是用PHP的數(shù)組并將其編碼為類本身。這個類也能外源獲取數(shù)據(jù),如INI或是XML文件。
數(shù)據(jù)對象映射模式,是將對象和數(shù)據(jù)存儲映射起來,對一個對象的操作會映射為對數(shù)據(jù)存儲的操作。
在代碼中實現(xiàn)數(shù)據(jù)對象映射模式,實現(xiàn)一個ORM類,將復(fù)雜的sql語句映射成對象屬性的操作。對象關(guān)系映射(Object Relational Mapping,ORM)
ha_cl表
Hacl.php
<?phpnamespace 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 setha_cl_code = '{$this->haclcode}',ha_cl_name = '{$this->haclname}',hacls = '{$this->hacls}'where ID = {$this->id}limit 1");}}Factory.php
<?phpnamespace 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
<?phpnamespace 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 = '測試內(nèi)容';}}$page = new Page();$page->index(); 使用工廠模式會多次創(chuàng)建對象Hacl,浪費資源,如果將對象作為參數(shù)傳遞,一方面會帶來額外的使用成本,另外如果很多地方都用到這個對象很容易發(fā)生錯誤,因此在工廠模式中使用注冊樹模式來解決這個問題。
以上內(nèi)容給大家介紹了php設(shè)計模式之數(shù)據(jù)對象映射模式,希望對大家有所幫助!
新聞熱點
疑難解答