加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP设计模式之:数据映射模式的介绍

发布时间:2023-09-18 10:41:54 所属栏目:PHP教程 来源:
导读:php中的设计模式中有很多的各种模式了,在这里我们来为各位介绍一个不常用的数据映射模式吧,希望文章能够帮助到各位。

之前的几种设计模式,都是大大提高了PHP代码的可读性、可维护性。但是,在WEB应用中还有更重
php中的设计模式中有很多的各种模式了,在这里我们来为各位介绍一个不常用的数据映射模式吧,希望文章能够帮助到各位。

之前的几种设计模式,都是大大提高了PHP代码的可读性、可维护性。但是,在WEB应用中还有更重要的需求与挑战,那就是:数据库应用。可之前的设计模式,都没有涉及于此。今天写到的,数据映射模式就是能够更好的组织应用程序与数据库进行交互。

对于博主目前使用的TP框架,其核心文件Model.class.php就是实现了ORM和ActiveRecords模式,在项目中所有的模型也都是继承这个模型类。
好吧,还是不丢人说这些废话了,自己参考编写整理了一份实例,给大家分享一下,互相交流。

创建一个DB类文件 Db.class.php

<?php
/*
 * 数据库中间层实现类
 */
class Db {
    public static $db = null;
    private $_dbh = null;
    public static function getInstance() {
        if( self::$db == null ){
            self::$db = new self(BACKEND_DBHOST ,BACKEND_DBUSER ,BACKEND_DBPW ,BACKEND_DBNAME);
        }
        return self::$db;
    }
 
    private function __construct( $host ,$user ,$pass ,$dbname ){
        try {
            $this->_dbh = new PDO('mysql:dbname='.$dbname.';host='.$host,$user,$pass);
            $this->_dbh->query('SET NAMES '. BACKEND_DBCHARSET);
            $this->_dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
            $this->_dbh->setAttribute(PDO::ATTR_ERRMODE, true);
        } catch (PDOException $e) {
            throw new Exception('Can not connect db');
        }
    }
    public function getOne($sql){
        try {
            $rs = $this->_dbh->query($sql);
            $result = $rs->fetch(PDO::FETCH_ASSOC);
            if(!empty($result)) {
                return $result;
            }
        } catch (PDOException $e) {
            throw new Exception($this->_dbh->errorInfo());
        }
        return false;
    }
 
    public function getAll($sql){
        try {
            $rs = $this->_dbh->query($sql);
            $result = $rs->fetchAll(PDO::FETCH_ASSOC);
            if(!empty($result)) {
                return $result;
            }
        } catch (PDOException $e) {
            throw new Exception($this->_dbh->errorInfo());
        }
        return false;
    }
 
    public function exec($sql){
        try {
            $exec = $this->_dbh->exec($sql);
        } catch (PDOException $e){
            throw new Exception($this->_dbh->errorInfo());
        }
        return $exec;
    }
 
    public function getLastId()
    {
        return $this->_dbh->lastInsertId();
    }
}
?>

数据映射类 Table.class.php

<?php
/**
 * 数据映射类
 * 部分代码来源TP框架
 * 使用相关魔术方法 则映射的表修改字段后无需修改属性值
 */
class Table{
 
    // 数据信息
    protected $data = array();
 
    // 数据信息
    protected $db = null;
 
    // 表信息
    protected $tableName = '';
    public function __construct() {
        $this->db = Db::getInstance();
    }
 
    /**
     * 设置数据对象的值
     */
    public function __set($name,$value) {
        // 设置数据对象属性
        $this->data[$name] = $value;
    }
    /**
     * 获取数据对象的值
     */
    public function __get($name) {
        return isset($this->data[$name])?$this->data[$name]:null;
    }
 
    /*
     * 添加
     * 修改、删除也和添加类似,就不一一列举了
     */
    public function add() {
        $data = $this->data;
        foreach($data as $k=>$v) {
            $fieldArr[] = $k;
            $valueArr[] = "'".$v."'";
        }
        $fields = implode(',', $fieldArr);
        $values = implode(',', $valueArr);
        $sql = 'INSERT INTO '.$this->tableName.' ('.$fields.') VALUES ('.$values.')';
        $result = $this->db->exec($sql);
        if($result) {
            return $this->db->getLastId();
        } else {
            return false;
        }
    }
}
?>

表对应的类文件 UserTable.class.php

<?php
/**
 * 数据映射到表
 * 一般根据表的结构由工具自动生成,比如Yii框架等。
 */
class UserTable extends Table {
    protected $tableName = 'user';
}
?>

使用方式 index.php

<?php
/**
 * 数据库配置文件
 */
define('BACKEND_DBHOST', 'localhost');
define('BACKEND_DBUSER', 'root');
define('BACKEND_DBPW', '');
define('BACKEND_DBNAME', 'test');
define('BACKEND_DBCHARSET', 'utf-8');
/*
 * 这里实例化对象时可以使用之前介绍的工厂模式和注册模式,来实例化和管理实例化对象
 * TP框架中的D方法就是做了这部分工作
 */
$UserTable = new UserTable();
$UserTable->username = 'Anrai';
$UserTable->mobile = '123456789';
$UserTable->email = 'huanglei.web@gmail.com';
echo $UserTable->add();
/*
数据表sql
CREATE TABLE `user` (
 `uid` int(11) NOT NULL AUTO_INCREMENT,
 `username` varchar(30) NOT NULL,
 `mobile` varchar(11) NOT NULL DEFAULT '0',
 `email` varchar(60) NOT NULL DEFAULT '0',
 PRIMARY KEY (`uid`),
 KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
*/ ?>

 

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章