Design Patterns Reference: Data Access Object DAO

“The Data Access Object Design Pattern describes the creation of an object that provides transparent access to any data source.”

/**
* Data Access Object Pattern Example
*/

/**
* first we define the abstract base DAO class,
* which, of course, thus MUST be extended to be used
* to note:
* – the connection is internally referenced,
* allowing multiple simultaneous connections and tables
* – the fetch and update methods are wonderfully abstract
* untied to table name, key, or value
*/
abstract class baseDAO
{
private $__connection;

public function __construct()
{
$this->__connectToDB(DB_USER, DB_PASS, DB_HOST, DB_DATABASE);
}

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($keyedArray)
{
$sql = “update {$this->_tableName} set “;

$updates = array();
foreach ($keyedArray as $column=>$value){
$updates[] = “{$column}='{$value}'”;
}

$sql .= implode(‘,’, $updates);
$sql .= “where {$this->_primaryKey}='{$keyedArray[$this->_primaryKey]}'”;

mysql_query($sql, $this->__connection);
}
}

/**
* Finally, let’s extend with a child class
* mapped to a specific table
*/

class userDAO extends baseDAO
{
protected $_tableName = ‘userTable’;
protected $_primaryKey = ‘id’;

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

/**
* Example of use
* DB connect data, of course, would be elsewhere and flexible
*/

define(‘DB_USER’,’user’);
define(‘DB_PASS’,’pass’);
define(‘DB_HOST’,’localhost’);
define(‘DB_DATABASE’,’test’);

/** fetch row id 1 **/
$user = new userDAO();
$userDetailsArray = $user->fetch(1);

/** update row id 1 **/
$updates = array(‘id’=>1, ‘firstName’=>’aaron’);
$user->update($updates);

/** get users with first name aaron **/
$allAarons = $user->getUserByFirstName(‘aaron’);

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

Comments are closed.