php中的設(shè)計(jì)模式中有很多的各種模式了,在這里我們來(lái)為各位介紹一個(gè)不常用的數(shù)據(jù)映射模式吧,希望文章能夠幫助到各位。
之前的幾種設(shè)計(jì)模式,都是大大提高了PHP代碼的可讀性、可維護(hù)性。但是,在WEB應(yīng)用中還有更重要的需求與挑戰(zhàn),那就是:數(shù)據(jù)庫(kù)應(yīng)用。可之前的設(shè)計(jì)模式,都沒(méi)有涉及于此。今天寫(xiě)到的,數(shù)據(jù)映射模式就是能夠更好的組織應(yīng)用程序與數(shù)據(jù)庫(kù)進(jìn)行交互。
博主這兩天也是花了點(diǎn)時(shí)間對(duì),這種模式有了那么一點(diǎn)的了解。斗膽在這個(gè)里獻(xiàn)丑,按照自己的理解,寫(xiě)一點(diǎn)東西與大家分享,互相學(xué)習(xí)。
當(dāng)然說(shuō)到數(shù)據(jù)映射模式,就不得不提到對(duì)象關(guān)系映射(Object Relational Mapping,簡(jiǎn)稱ORM),用于實(shí)現(xiàn)面向?qū)ο缶幊陶Z(yǔ)言里不同類型系統(tǒng)的數(shù)據(jù)之間的轉(zhuǎn)換。一般ORM框架對(duì)付簡(jiǎn)單的應(yīng)用系統(tǒng)來(lái)說(shuō)都能滿足基本需求,可以大大降低開(kāi)發(fā)難度,提高開(kāi)發(fā)效率,但是它在SQL優(yōu)化方面,肯定是比純SQL語(yǔ)言要差很多,對(duì)復(fù)雜關(guān)聯(lián)、SQL內(nèi)嵌表達(dá)式的處理都不是很理想。
對(duì)于博主目前使用的TP框架,其核心文件Model.class.php就是實(shí)現(xiàn)了ORM和ActiveRecords模式,在項(xiàng)目中所有的模型也都是繼承這個(gè)模型類。
好吧,還是不丟人說(shuō)這些廢話了,自己參考編寫(xiě)整理了一份實(shí)例,給大家分享一下,互相交流。
首先我們需要一個(gè)數(shù)據(jù)庫(kù)中間層實(shí)現(xiàn)類,使用pdo進(jìn)行數(shù)據(jù)庫(kù)訪問(wèn)。當(dāng)然這個(gè)類不是今天的重點(diǎn),我也是從網(wǎng)上拷來(lái)的,可以直接忽略。
創(chuàng)建一個(gè)DB類文件 Db.class.php
<?php
/*
* 數(shù)據(jù)庫(kù)中間層實(shí)現(xiàn)類
*/
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();
}
}
?>
數(shù)據(jù)映射類 Table.class.php
<?php
/**
* 數(shù)據(jù)映射類
* 部分代碼來(lái)源TP框架
* 使用相關(guān)魔術(shù)方法 則映射的表修改字段后無(wú)需修改屬性值
*/
class Table{
// 數(shù)據(jù)信息
protected $data = array();
// 數(shù)據(jù)信息
protected $db = null;
// 表信息
protected $tableName = '';
public function __construct() {
$this->db = Db::getInstance();
}
/**
* 設(shè)置數(shù)據(jù)對(duì)象的值
*/
public function __set($name,$value) {
// 設(shè)置數(shù)據(jù)對(duì)象屬性
$this->data[$name] = $value;
}
/**
* 獲取數(shù)據(jù)對(duì)象的值
*/
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;
}
}
}
?>
表對(duì)應(yīng)的類文件 UserTable.class.php
<?php
/**
* 數(shù)據(jù)映射到表
* 一般根據(jù)表的結(jié)構(gòu)由工具自動(dòng)生成,比如Yii框架等。
*/
class UserTable extends Table {
protected $tableName = 'user';
}
?>
使用方式 index.php
<?php
/**
* 數(shù)據(jù)庫(kù)配置文件
*/
define('BACKEND_DBHOST', 'localhost');
define('BACKEND_DBUSER', 'root');
define('BACKEND_DBPW', '');
define('BACKEND_DBNAME', 'test');
define('BACKEND_DBCHARSET', 'utf-8');
/*
* 這里實(shí)例化對(duì)象時(shí)可以使用之前介紹的工廠模式和注冊(cè)模式,來(lái)實(shí)例化和管理實(shí)例化對(duì)象
* TP框架中的D方法就是做了這部分工作
*/
$UserTable = new UserTable();
$UserTable->username = 'Anrai';
$UserTable->mobile = '123456789';
$UserTable->email = 'huanglei.web@gmail.com';
echo $UserTable->add();
/*
數(shù)據(jù)表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
*/ ?>
新聞熱點(diǎn)
疑難解答