数据库访问对象模式
php设计模式之3-数据库访问对象模式.
适配器问题:重复的不通参数重复同样的操作.就那最常用的操作数据库CRUD应用程序为主要案例
解决方案:设计出基本整体操作类,对不通的表和主键采用另定义类集成基本操作类.设计出来的基本操作类为抽象类,不进行实例化,只提供方法.
实例举例:
<?php
abstract class forasp_book{
private $_connection;
public function __consturct(){
$this->connection(DBUSER,DB_PASS,DB_HOST,DB_DATADASE);
}
private function connection($user,$pw,$host,$db){
$this->_connection = mysql_connect($host,$user,$pw);
mysql_selectdb($db);
}
public function fetch($value,$key=null){
if(is_null($key))$key=$this->_primaryKey;
$sql = "select * from {$this->_tableName} where {$key} = '{$value}'";
$resaults = mysql_query($sql,$this->_connection);
$rows = array();
while($resault = mysql_fetch_array($resaults)){
$rows[] = $resault;
}
return $rows;
}
public function update($keyArray){
$sql = "update {$this->tableName} set";
$updates = array();
foreach($keyarray as $col=>$val){
$updates[] = "{$col} = '{$val}'";
}
$sql. = implode($updates,",");
$sql. = " where {$this->primaryKey} = '{$keyArray[$this->_primaryKey]}'";
mysql_query($sql,$this->_connection);
}
}
/////////以上是抽象基类,也即是常操作类.
//下面是一个查询用户名的类,继承上面的抽象基类
class user extends forasp_book{
protected $tableName = "userTable";
protected $primaryKey = "id";
public function getUserName($name){
$resault = $this->fetch($name,"name");
return $resault;
}
}
define(DB_HOST,);
define(DBUSER,);
define(DB_PASS,);
define(DB_DATADASE,);
$user = new user();
$userinfo = $user->fetch(1);
$updates = array("id"=>1,"name"="forasp.cn");
$user->update($updates);
$all = $user->getUserName("forasp.cn");
?>
总结:将重复带有变量的操作做为一个抽象类,并有用方法,通过子类的参数定义来调用不通的内容.返回的是数据内容.
转载%77%77%77请%2E%66%6F%72%61%73%70%2E%63%6E注明