數據訪問對象模式+建造者模式

<?php
/**
 * @author  v.r    
 * 
 * @example
 * 數據訪問對象模式 + 建造者模式 構建數據庫驅動
 * 數據訪問對象設計模式描述瞭如何建立提供透明的訪問任何數據源的對象
 * 列子:
 *  以mysql爲列子
 * 
 * 解決的問題:
 * 重複與數據源抽象化
 * 
 * 
 * @copyright copyright information
 * 
 */
class DATABASE_CONFIG {
	public $default = array(
		'host' => '127.0.0.1',
		'port' => 3306,
		'user' => 'test123',
		'pass' => 'abc',
		'database' => 'user',
	);

	public $common_db = array(
		'host' => '192.168.81.1',
		'port' => 3306,
		'user' => 'dev234',
		'pass' => 'v.r%',
		'database' => 'common_db',

	);
	public function __construct() {}
}

abstract class BaseDAO 
{
	private $connection;
	protected $configs;
	protected $primaryKey = '';
	protected $tableName = '';
	protected $useDbConfig = 'default';


	public function __construct() 
	{
		$this->bulid();
	}

	public function bulid() {
	    $this->configs = get_object_vars(new DATABASE_CONFIG);
	    $this->connectionToDB($this->configs[$this->useDbConfig]['user'],
	    	$this->configs[$this->useDbConfig]['pass'],
	    	$this->configs[$this->useDbConfig]['host'],
	    	$this->configs[$this->useDbConfig]['database']);
	}


	public function connectionToDB($user,$pass,$host,$database) 
	{
		$this->connection = mysql_connect($host,$user,$pass);
		mysql_select_db($database,$this->connection);
	}

	public function fetch ($value,$key=null) 
	{
		if (is_null($key)) {
			$key = $this->primaryKey;
		}

		$sql  = "SELECT *  FROM  {$this->tableName}  WHERE {$key} = '{$value}'";
         
        $results = mysql_query($sql,$this->connection);

        $rows = array();

        while ($result  = mysql_fetch_array($results)) {
        	$rows[] = $result;

        }

        return $rows;
	}


	public function update($list) 
	{
		$uplist = ''; 
		$where = 0;   
		foreach ($list as $k => $v) {
			if (in_array($k, $this->fields)) {
				if ($k == $this->fields['pk']) {
					$where = "`$k`=$v";
				} else {
					$uplist .= "`$k`='$v'".",";
				}
			}
		}

		$uplist = rtrim($uplist,',');
		$sql = "UPDATE `{$this->tableName}` SET {$uplist} WHERE {$where}";
		mysql_query($sql,$this->connection);
	}
}



class userDAO extends BaseDAO
{
	protected $useDbConfig = 'default';
	protected $primaryKey = 'id';
	protected $tableName = 'user';

	public function getUserByFirstName($name) 
	{
		$result = $this->fetch($name,'firstName');
		return $result;
	}
}

$user = new userDAO;
$userinfo = $user->fetch(1);  //show id eq 1 
$updates = array('id'=>1,'firstName'='v.r'); 
$user->update($updates);  // update id = 1



class commonDAO extends BaseDAO {
	protected $useDbConfig = 'common_db';
	protected $primaryKey = 'id';
	protected $tableName = 'common_user';
	public function getUserByUUID($UUID) 
	{
		$result = $this->fetch($UUID,'uuid');
		return $result;
	}
}


}

$common = new commonDAO;
$common = $common->fetch(1);  //show id eq 1 
$updates = array('id'=>1,'firstName'='v.r'); 
$common->update($updates);  // update id = 1



#end  Script
相關文章
相關標籤/搜索