php設計模式 資料對象映射模式,php設計模式_PHP教程

來源:互聯網
上載者:User

php設計模式 資料對象映射模式,php設計模式


資料對象映射模式,是將對象和資料存放區映射起來,對一個對象的操作會映射為對資料存放區的操作。

在代碼中實現資料對象映射模式,實現一個ORM類,將複雜的sql語句映射成對象屬性的操作。對象關係映射(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 set ha_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 = '測試內容';    }}$page = new Page();$page->index();

使用原廠模式會多次建立對象Hacl,浪費資源,如果將對象作為參數傳遞,一方面會帶來額外的使用成本,另外如果很多地方都用到這個對象很容易發生錯誤,因此在原廠模式中使用註冊樹模式來解決這個問題。

http://www.bkjia.com/PHPjc/1104652.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1104652.htmlTechArticlephp設計模式 資料對象映射模式,php設計模式 資料對象映射模式,是將對象和資料存放區映射起來,對一個對象的操作會映射為對資料存放區的...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.