php架構Yaf PDO封裝類和ORM整合,yaf本身不帶orm資料封裝,我們可以建立在pdo上實現自己的封裝。
一:首先我們使用php的單例模式,建立基類。library\Base.php
<?php
class Base {
/**
* 設計模式之單例模式
* $_instance必須聲明為靜態私人變數
*/
//儲存例執行個體在此屬性中
private static $_instance;
//單例方法
public static function getInstance() {
$class_name = get_called_class();
if (!isset(self::$_instance[$class_name])) {
self::$_instance[$class_name] = new $class_name;
}
/*@var $var $class_name*/
return self::$_instance[$class_name];
}
//阻止使用者複製對象執行個體
public function __clone() {
trigger_error('Clone is not allow', E_USER_ERROR);
}
}
二:以註冊使用者資訊為例,$userInfo為表單傳入的資料,我們要插入到資料庫
我們建立了userModel類
class userModel extends Model {
}
$uid = userModel::getInstance()->add($userInfo);
我們用add方法插入資料,我們需要建立這個方法在Model中
三:ORM 整合到library\Model.php
<?php
class Model extends Base {
//主鍵名稱
public $primaryKey = 'id';
public $orderKey = 'id';
//資料表欄位 欄位名 => 欄位初始值
public $fileds = array();
//唯寫緩衝
protected $onlyCache = false;
//資料表名稱
protected $table;
protected $readDb = false;
protected $cacheObj;
protected $dbObj;
function __construct() {
$this->init();
}
public function init() {
$this->table = str_replace('Model', '', get_called_class());
$this->dbObj = Db_Pdo::getInstance();
//匯入db配置
$config = Common::getConfig('database');
$this->dbObj->loadConfig($config);
}
/**
* 新增資料
* @param type $parmas
* @return type
*/
public function add($parmas) {
if (!$parmas || !is_array($parmas))
return false;
$parmas = $this->initFields($parmas);
if (!$parmas)
return false;
$time = date("Y-m-d H:i:s");
$parmas['create_time'] = $time;
$parmas['update_time'] = $time;
$id = $this->insertDB($parmas);
if (!$id) {
return false;
}
return $id;
}
}
/**
* db新增
* @param type $parmas
* @return boolean
*/
private function insertDB($parmas) {
if ($this->onlyCache) {
return true;
}
if (!$parmas || !is_array($parmas)) {
return false;
}
$ret = $this->dbObj->insert($this->table, $parmas);
return $ret;
}
我們初始化了db配置,引用pdo操作類,在add方法中執行力pdo資料insertDB操作
四:最後我們要在pdo操作類中定義insert方法 執行最終的插入library/Db/Pdo.php
<?php
class Db_Pdo {
protected static $instance = null;
public static $TIMESTAMP_WRITES = false;
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function loadConfig($db) {
$this->configMaster($db['m']['host'], $db['m']['name'], $db['m']['user'], $db['m']['pwd'], $db['m']['port']);
$this->configSlave($db['s']['host'], $db['s']['name'], $db['s']['user'], $db['s']['pwd'], $db['s']['port']);
}
public function insert($table, $params = array(), $timestamp_this = null, $break = false) {
if (is_null($timestamp_this)) {
$timestamp_this = self::$TIMESTAMP_WRITES;
}
// first we build the sql query string
$columns_str = '(';
$values_str = 'VALUES (';
$add_comma = false;
// add each parameter into the query string
foreach ($params as $key => $val) {
// only add comma after the first parameter has been appended
if ($add_comma) {
$columns_str .= ', ';
$values_str .= ', ';
} else {
$add_comma = true;
}
// now append the parameter
$columns_str .= "$key";
$values_str .= ":$key";
}
// add the timestamp columns if neccessary
if ($timestamp_this === true) {
$columns_str .= ($add_comma ? ', ' : '') . 'date_created, date_modified';
$values_str .= ($add_comma ? ', ' : '') . time() . ', ' . time();
}
// close the builder strings
$columns_str .= ') ';
$values_str .= ')';
// build final insert string
$sql_str = "INSERT INTO $table $columns_str $values_str";
if ($break) {
return $sql_str;
}
// now we attempt to write this row into the database
try {
$pstmt = $this->getMaster()->prepare($sql_str);
// bind each parameter in the array
foreach ($params as $key => $val) {
$pstmt->bindValue(':' . $key, $val);
}
$pstmt->execute();
$newID = $this->getMaster()->lastInsertId();
// return the new id
return $newID;
} catch (PDOException $e) {
if (self::$SHOW_ERR == true) {
throw new Exception($e);
}
$this->pdo_exception = $e;
return false;
} catch (Exception $e) {
if (self::$SHOW_ERR == true) {
throw new Exception($e);
}
$this->pdo_exception = $e;
return false;
}
}
}