php设计模式 数据对象映射模式
2016-03-02 15:40
696 查看
数据对象映射模式,是将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作。
在代码中实现数据对象映射模式,实现一个ORM类,将复杂的sql语句映射成对象属性的操作。对象关系映射(Object Relational Mapping,ORM)
ha_cl表
Hacl.php
Factory.php
Register.php
index.php
使用工厂模式会多次创建对象Hacl,浪费资源,如果将对象作为参数传递,一方面会带来额外的使用成本,另外如果很多地方都用到这个对象很容易发生错误,因此在工厂模式中使用注册树模式来解决这个问题。
在代码中实现数据对象映射模式,实现一个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,浪费资源,如果将对象作为参数传递,一方面会带来额外的使用成本,另外如果很多地方都用到这个对象很容易发生错误,因此在工厂模式中使用注册树模式来解决这个问题。
相关文章推荐
- oRTP源码分析
- PHP扩展加载错误
- PHP扩展加载错误
- sftp与ftp用法
- php mb_strlen 获取字符串的长度
- php mb_substr 获取字符串的部分
- php7 php-fpm 显示空白页原因一例
- php try() catch() : 捕捉异常,抛出异常
- PHP内核探索:新垃圾回收机制说明
- Swagger PHP使用指南
- php 得到所选择的mysql数据库名称和链接信息
- ubuntu +phpstorm 配置phpunit
- PHP empty(),isset()与is_null()的实例测试
- 本机php环境搭建教程:windows环境…
- easyphp环境配置
- 只需要四步,就能完成PHP搭建
- Java调用PHP 实例
- php 引用(&)详解
- YII 页面缓存
- PHP/Java Bridge 实例 | PHP 调用 Java 实例