Ver Mensaje Individual
  #12 (permalink)  
Antiguo 02/01/2008, 14:03
Avatar de pragone
pragone
 
Fecha de Ingreso: diciembre-2007
Ubicación: Madrid
Mensajes: 223
Antigüedad: 16 años, 5 meses
Puntos: 2
Re: Ayuda con mi modelo de objetos

Hola,

bulter, me gusta mucho la sintaxis con la que queda (aunque no puedo decir lo misma de los comentarios ), pero no has pensado en agregarle una función left_join que reciba la tabla y la condición de unión?... por lo que pude ver sólo puedes hacer productos cartesianos.

Computer Xtress, creo que lo que comentó GatorV es lo apropiado (así funciona de hecho la clase de bulter.... el método select no pertenece a la clase que puso sino a la clase de conexión a la base de datos).
Si me permites hacerte una recomendación adicional, me gusta siempre que hago una clase de acceso a BD que tenga built-in la capacidad de hacer accesos diferentes para lectura y escritura.

Aquí te dejo un ejemplo de clase que utilizo en PHP5DBObject... un framework para ActiveRecord en el que estoy trabajando, puedes ver un ejemplo del concepto en http://pragone.com/proyectos/php5dbo...ork-en-php5/10 ... se monta sobre MDB2 de PEAR:

Código PHP:
<?php
/*

PHP5DBObject is a PHP5 Framework for easing the access to the DB from your application
Copyright (C) 2007  Paolo Ragone

This file is part of PHP5DBObject.

PHP5DBObject is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or any later version.

PHP5DBObject is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with PHP5DBObject.  If not, see <http://www.gnu.org/licenses/lgpl.html>.


 */

/**
 * This class implements a convenience method to access the DB and perform queries.
 * The main benefit of this class is that it already takes care of using (optionally) two different connections: one for all read-related queries and one for manipulation/write queries.
 * 
 * Using a class like this is a good idea for some reasons:
 * - Scalability: Probably the first DB-related scalability action you'll take is to use a master-slave replicated environment, when that time comes you'll regret not having separated all read from write queries.
 * - Security: One good way to achieve the point above is to use different users/passwords to access the DB. This also allows you to (under certain circumstances) have better security.
 *
 * Possible ways to enhance:
 * - Create options:
 *   - convert dates... to automagically convert 
 *     date, time and timestamp to unix timestamp
 * @package PHP5DBObject
 * @subpackage db
 * @version 1.0
 * @author Paolo Ragone <[email protected]>
 * @link http://pragone.com -> Author's Home Page
 * @copyright Copyright (c) 2007, Paolo Ragone
 * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License
 * filesource
 */


require_once 'MDB2.php';

/**
 * This class implements a convenience method to access the DB and perform queries.
 * The main benefit of this class is that it already takes care of using (optionally) two different connections: one for all read-related queries and one for manipulation/write queries.
 * 
 * Using a class like this is a good idea for some reasons:
 * - Scalability: Probably the first DB-related scalability action you'll take is to use a master-slave replicated environment, when that time comes you'll regret not having separated all read from write queries.
 * - Security: One good way to achieve the point above is to use different users/passwords to access the DB. This also allows you to (under certain circumstances) have better security.
 *
 * @package PHP5DBObject
 * @subpackage db
 * 
 */
class RWDBAccess implements DBManager {
    
    
/**
     * The MDB2 read-only connection. In case only a read-write connection was specified, this will reference the same $conn_w connection
     * @var MDB2_Connection
     * @see RWDBAccess::$conns_w
     */
    
protected $conn_r null;
    
    
/**
     * The MDB2 write-only connection
     * @var MDB2_Connectin
     */
    
protected $conn_w null;
    
    
/**
     * Constructor method for the class. It creates "lazy connections" to the DB (connections that are actualy established only when the first query is executed). It expects an associative array with some of the following keys: 'ro' (read only), 'wo' (write only) and/or rw (read write). Which must contain the dsn's or configuration arrays expected by MDB2 factory method.
     * You should provide at least a connection for read access and one for write access, this can be either: ro & rw, rw & wo, ro & rw, only a rw.
     * 
     */
    
function __construct($dsn) {
        if (isset(
$dsn['wo'])) $dsn_w 'wo';
        elseif (isset(
$dsn['rw'])) $dsn_w 'rw';
        else throw new 
RWDBAccessException("You must supply a valid DSN with write access (either 'wo' or 'rw')");
        
        if (isset(
$dsn['ro'])) $dsn_r 'ro';
        elseif (isset(
$dsn['rw']) && is_array($dsn['rw'])) $dsn_r 'rw';
        else throw new 
RWDBAccessException("You must supply a valid DSN with read access (either 'ro' or 'rw')");
        
        
$temp =& MDB2::factory($dsn[$dsn_w]);
        if (
PEAR::isError($temp)) throw new RWDBAccessException('Error creating write connection to the database, error: ' $temp->getMessage());
        
$this->conn_w =& $temp;
        
        if (
$dsn_r != $dsn_w) {
            
$temp =& MDB2::factory($dsn[$dsn_r]);
            if (
PEAR::isError($temp)) throw new RWDBAccessException('Error creating read connection to the database, error: ' $temp->getMessage());
            
$this->conn_r =& $temp;
        } else {
            
$this->conn_r =& $this->conn_w;
        }
        
$this->conn_r->setFetchMode(MDB2_FETCHMODE_ASSOC);
    }
    
    function 
__destruct() {
        if (
MDB2::isConnection($this->conn_w)) $this->conn_w->disconnect();
        
$this->conn_w null;
        if (
$this->conn_r != null && MDB2::isConnection($this->conn_r)) $this->conn_r->disconnect();
        
$this->conn_r null;
    }
    
    
/**
     * This function returns one row from a select query.
     */
    
public function &getOneRow($sql$params$data_types null) {
        if (empty(
$params)) {
            
$result $this->conn_r->query($sql);
        } else {
            
$st $this->conn_r->prepare($sql);
            
$result $st->execute($params);
        }
        
$result->setResultTypes($data_types);
        if (
PEAR::isError($result)) throw new RWDBAccessException("Error executing query:\n$sql\nOn connection: $connection\nError:" $result->getMessage());
        
        
$row $result->fetchRow();
        
$result->free();
        return 
$row;
    }

    public function &
getMultipleRows($sql$params$data_types null) {
        if (empty(
$params)) {
            
$result $this->conn_r->query($sql$data_types);
        } else {
            
$st $this->conn_r->prepare($sql$data_types);
            
$result $st->execute($params);
            
$st->free();
        }
        if (
PEAR::isError($result)) throw new RWDBAccessException("Error executing read query:\n$sql\nError:" $result->getMessage());
        
        
$res = array();
        while (
$row $result->fetchRow()) {
            
$res[] = $row;
        }
        
$result->free();
        return 
$res;
    }
    
    public function 
execute($sql$params) {
        if (empty(
$params)) {
            
$result $this->conn_w->exec($sql);
        } else {
            
$st $this->conn_w->prepare($sqlnullMDB2_PREPARE_MANIP);
            
$result $st->execute($params);
            
$st->free();
        }
        if (
PEAR::isError($result)) throw new RWDBAccessException("Error executing query:\n$sql\nOn connection: $connection\nError:" $result->getMessage());
        return 
$result;
    }

    public function 
execute_r($sql$params) {
        if (empty(
$params)) {
            
$result $this->conn_r->exec($sql);
        } else {
            
$st $this->conn_r->prepare($sqlnullMDB2_PREPARE_MANIP);
            
$result $st->execute($params);
            
$st->free();
        }
        if (
PEAR::isError($result)) throw new RWDBAccessException("Error executing query:\n$sql\nOn connection: $connection\nError:" $result->getMessage());
        return 
$result;
    }

    public function 
insert($sql$params) {
        if (empty(
$params)) {
            
$result $this->conn_w->exec($sql);
        } else {
            
$st $this->conn_w->prepare($sql);
            
$result $st->execute($params);
            
$st->free();
        }
        if (
PEAR::isError($result)) throw new RWDBAccessException("Error executing query:\n$sql\nOn connection: $connection\nError:" $result->getMessage());
        return 
$this->conn_w->lastInsertID();
    }
}

class 
RWDBAccessException extends Exception {
    public function 
__construct($message) {
        
parent::__construct($message0);
    }
    
    public function 
__toString() {
        return 
__CLASS__ ": {$this->message}\n";
    }
}

?>