Php design mode: Data Object ing mode; php design mode
The Data Object ing mode maps objects and data storage. operations on an object are mapped to operations on data storage.
Implement the Data Object ing mode in the code, implement an ORM class, and map complex SQL statements into object attributes. Object Relational ing (ORM)
Ha_cl table
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); // different table IDs indicate different objects 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 = 'test name'; $ this-> test (); echo 'OK';} function test () {$ hacl = Baobab \ Factory: getHacl (13); $ hacl-> hacls = 'test content ';}} $ page = new Page (); $ page-> index ();
In factory mode, object Hacl is created multiple times, which wastes resources. If an object is passed as a parameter, on the one hand, additional costs are incurred, in addition, if this object is used in many places, errors may easily occur. Therefore, use the registration tree mode in factory mode to solve this problem.