Interfaces necesarias:
DataSourceInterface:
Código PHP:
<?php
interface DataSourceInterface {
public function bind();
public function getData();
}
?>
DBAccessInterface:
Código PHP:
<?php
interface DBAccessInterface {
public function Connect();
public function Query($query);
public function Disconnect();
}
?>
DBResultInterface.php
Código PHP:
<?php
interface DBResultInterface {
public function fetchRow();
public function numRows();
}
?>
Luego viene el acceso a datos (es una clase muy sencilla que seguramente deberá ser completada):
DBAccess.php:
Código PHP:
<?php
class DBAccess implements DBAccessInterface {
private $host;
private $user;
private $pass;
private $db;
private $link;
public function __construct($host, $user, $pass, $db ) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->db = $db;
}
public function Connect() {
$this->link = mysql_connect( $this->host, $this->user, $this->pass );
if( $this->link ) {
mysql_select_db( $this->db );
} else {
throw new Exception( 'MySQL Error: ' . mysql_error() );
}
}
public function Query($query) {
$result = mysql_query( $query, $this->link );
if( is_bool( $result ) ) {
return $result;
} else {
return new DBResult( $result );
}
}
public function Disconnect() {
mysql_close( $this->link );
}
}
?>
DBResult.php
Código PHP:
<?php
class DBResult implements DBResultInterface {
private $result;
public function __construct( $result ) {
$this->result = $result;
if( is_bool( $result ) ) {
throw new Exception( '$result parece ser un booleano, no un resultado exitoso de una DB: ' . mysql_error() );
}
}
public function fetchRow() {
return mysql_fetch_row( $this->result );
}
public function numRows() {
return mysql_num_rows( $this->result );
}
public function __destruct() {
mysql_free_result( $this->result );
}
}
?>
Luego viene el DataSource o la fuente de datos:
SQLDataSource:
Código PHP:
<?php
class SQLDataSource implements DataSourceInterface {
private $query = '';
private $data = array();
private $dbh = null;
public function __construct($dbh, $query) {
if( !($dbh instanceof DBAccess ) ) {
throw new Exception( '$dbh debe implementar la interface DBAccess' );
}
$this->dbh = $dbh;
$this->query = $query;
}
public function bind() {
$result = $this->dbh->Query( $this->query );
if( $result->numRows() == 0 ) {
$this->data = array();
$result = null;
return;
}
$data = array();
while( $row = $result->fetchRow() ) {
if( count( $row ) == 2 ) { // cuando viene como valor, nombre
$data[$row[0]] = $row[1];
} else {
$data[] = $row[0];
}
}
$this->data = $data;
$result = null;
}
public function getData() {
return $this->data;
}
}
?>
.. Continua ..