Ver Mensaje Individual
  #7 (permalink)  
Antiguo 02/01/2008, 01:30
Avatar de bulter
bulter
 
Fecha de Ingreso: enero-2008
Mensajes: 137
Antigüedad: 16 años, 4 meses
Puntos: 20
Re: Ayuda con mi modelo de objetos

Podrias hacer lo aun mejor por ejemlo aqui tengo una adaptador para SELECT de la base de datos:

Código PHP:
<?php
/**
 * dGroup Framework
 *
 * @copyright   Copyright (c) 2007 dGroup Technologies
 * @license     Виж license.txt
 * @version     dGroup_Db_Adapter_Pdo_Select.php 0001 19-12-2007 14:42 (v0.0.1)
 */
 
 
require_once "Abstract.php";
 
 class 
dGroup_Db_Adapter_Pdo_Select{
    const 
DISTINCT     'distinct';
    const 
COLUMNS      'columns';
    const 
FROM         'from';
    const 
WHERE        'where';
    const 
GROUP        'group';
    const 
ORDER        'order';
    const 
LIMIT_COUNT  'limitcount';
    const 
LIMIT_OFFSET 'limitoffset';

    protected 
$parts = array(self::FROM         => array(),
                             
self::DISTINCT     => false,
                             
self::WHERE        => array(),
                             
self::ORDER        => array(),
                             
self::LIMIT_COUNT  => null,
                             
self::LIMIT_OFFSET => null);
    
    
/**
     * Where Bind Params
     */         
    
protected $_whereBindParam = array();

    
/**
     * PDO Object
     */         
    
protected $_connection;
    
    protected 
$_distinct;
    
    
/**
     * Взима текучия PDO адаптер
     */         
    
public function __construct($_connection){
        
$this->_connection $_connection;
    }
    
     
/**
     * Задава на заявката от къде трябва да избере данните.
     * 
     * @param string|array $name Името на таблицата
     * @param string|array $cols от кой редове да избира  
     * @throws  dGroup_Exception
     * @return object                
     */           
    
    
public function from($name$cols "*"){
        return 
$this->_from($name$cols);
    }      
    
    private function 
_from($name$cols){
        if(
is_array($name)){
            
$name $this->parts[self::FROM]["table"] = implode(", "$name);
        }elseif(
is_string($name)){
            
$name $this->parts[self::FROM]["table"] = $name;
        }else{
            throw new 
dGroup_Exception("Таблиците трябва да бъдат записани в стринг или масив.");
        }
        
        if(
is_array($cols)){
            
$cols $this->parts[self::FROM]["cols"] = implode(", "$cols);
        }elseif(
is_string($cols)){
            
$cols $this->parts[self::FROM]["cols"] = $cols;
        }else{
            throw new 
dGroup_Exception("Колоните трябва да бъдат записани в стринг или масив.");
        }
        
        return 
$this;
    }
    
    
/**
     * Задава на заявката, че трябва да избере само резултати който 
     * са различни.
     * 
     * @param boolen $distinct (false - по подразбиране)    
     * @param string|array $cols полетата по който да търси разликата               
     */         
    
    
public function distinct($distinct false$cols){
        
$this->parts[self::DISTINCT] = (bool)$distinct;
        if(
$cols){
            if(!
is_array($cols)){
                
$cols = array($cols);
            }
            
$this->_distinct implode($cols);
        }
        
        return 
$this;
    }
    
    
/**
     * Функцията where лимитира резултатите от базата данни,
     * като показва определени данни който се изискват при 
     * извеждането от базата данни.
     * Функцията има 1 задължителен параметър който е стринг
     * и показва какво точно се търси.
     * Пр: $dGroup->select()->from("dGroup", "*")->where("index = ?", 1)
     * В този случей резултатите който ше бъдат изведини съдържат
     * поле index със стойност 1. Зададените параметри за съвместимост
     * нямат ограничен брой.
     * Параметрите за съвместимост трябва да са зададени в същия ред 
     * както и при самата клауза.
     * Пр: where("index = ? and title = ?", "dGroup", 1)
     * В този случей ще се търси за index = dGroup и title = 1, а не за
     * index = 1 и title = dGroup
     * Ако вече е зададена 1 WHERE клауза се задава още една добавяйки
     * AND.
     * Пр: where("index = ?", 1)->where("title = ?", "dGroup")  
     * 
     * @param string $value
     * @return: object                                                                                             
     */         
    
    
public function where($value){
        if (
func_num_args() > 1) {
            
$val = array();
            for(
$i=0;$i<=func_num_args()-1;$i++){
                
$val[] = func_get_arg($i);
            }
            
$value $this->_where($value$val);
        }
        
        if (
$this->parts[self::WHERE]) {
            
$this->parts[self::WHERE][] = "AND ($value)";
        } else {
            
$this->parts[self::WHERE][] = "($value)";
        }
        
        return 
$this;
    }
    
    
/**
     * Функцията _where замества всички ? със
     * placeholder.      
     *
     * @param string $value е неконфигурираната WHERE клауза     
     * @param array $val съдържа стойностите за който трябва да се търси в базата данни. Те също се използват за създаването на placeholder като пред тях се добавя двуеточие ":"    
     *                        
     * @return: string $_where                         
     */              
    
    
public function _where($value$val){
        
$_keys explode("?"$value);
        
$_where "";
        for(
$i=0;$i<=count($_keys)-2;$i++){
           
$_where .= $_keys[$i].":".$val[$i+1];
           
$this->_whereBindParam[] = $val[$i+1];
           
        }

        return 
$_where;
    }
    
    
/**
     * Функцията настройва параметрите при WHERE клаузата
     * 
     * @param object $stmt          
     */         
    
    
protected function _bind($stmt){
        
$params count($this->_whereBindParam);
        for(
$i=0$i<=$params-1$i++){
            
$stmt->bindParam(":".$this->_whereBindParam[$i], $this->_whereBindParam[$i]);
        }
    }
    
    
/**
     * Настройва реда при който да се извежда информацията.
     * Посоката по подразбиране е DESC.
     * 
     * @param string|array $order 
     * @return Object                   
     */         
    
    
public function order($order){
        if(!
is_array($order)){
            
$order = array($order);
        }
        foreach (
$order as $value) {
            
$direction "DESC";
            if (
preg_match('/(.*)\s+(ASC|DESC)\s*$/i'$value$result)) {
                
$value trim($result[1]);
                
$direction $result[2];
            }
        }
        
        
$this->parts[self::ORDER][] = array($value$direction);
        return 
$this;
    }
    
    
/**
     * Настройва лимита на върнатите резултати.
     * 
     * @param   int $count  
     * @param   int $offset             
     * @return  mixed
     */         
    
    
public function limit($count null$offset null){
        
$this->parts[self::LIMIT_COUNT]  = (int)$count;
        
$this->parts[self::LIMIT_OFFSET] = (int)$offset;
        return 
$this;
    }
    
    
/**
     *  Слага кавички на стойноста му и я връща
     *  
     * @param string $value          
     */         
    
protected function quoteIdent($value){
        return (
'"' str_replace('"''""'$value) . '"');
    }
    
    
/**
     * Сглобява заявката след което я изпраща.
     * Връщания резултат са резултатите взети от базата данни.
     * 
     * @throws  dGroup_Exception
     * @return Object               
     */         
    
public function fetchAll(){
        
$sql "SELECT";
        if (
$this->parts[self::DISTINCT]) {
            
$sql .= "\nDISTINCT ".$this->_distinct."\n\t";
        }
        
        if(
$this->parts[self::FROM]){
            
$sql .= "\n".$this->parts[self::FROM]["cols"];
            
$sql .= "\nFROM\n\t";
            
$sql .= "\n".$this->parts[self::FROM]["table"]."\n\t";
        }
        
        if(
$this->parts[self::WHERE]){
            
$sql .= "\nWHERE\n\t".implode("\n\t"$this->parts[self::WHERE]);
        }
        
        if (
$this->parts[self::ORDER]) {
            
$sql .= "\nORDER BY\n\t";
            
$l = array();
            foreach (
$this->parts[self::ORDER] as $vals) {
                if (
is_array($vals)) {
                    
$l[] = $vals[0] . ' ' $vals[1];
                } else {
                    
$l[] = $vals;
                }
            }
            
$sql .= implode(",\n\t"$l);
        }
        
        
$count  "";
        
$offset "";
        if(
$this->parts[self::LIMIT_OFFSET]){
            
$offset = (int)$this->parts[self::LIMIT_OFFSET];
            
            
//Това ще зададе максималната стойност която цяло число може да съдържа в РНР
            
$count intval(9223372036854775807);
        }
        
        if(
$this->parts[self::LIMIT_COUNT]){
            
$count = (int)$this->parts[self::LIMIT_COUNT];
        }
        
        if(
$this->parts[self::LIMIT_COUNT] || $this->parts[self::LIMIT_OFFSET]){
            
$sql .= " LIMIT $count";
            if (
$offset 0) {
                
$sql .= " OFFSET $offset";
            }
        }

        
//Прави опит за изпращане и взимане на резултатите от заявката
        
try{
            
$stmt $this->_connection->prepare($sql);
            
$stmt->setFetchMode(PDO::FETCH_OBJ);
   
            
/**
             * Проверяваме дали има WHERE клауза и ако има такава
             * Викаме функцията _bind която ще зададе параметрите
             */                        
            
if($this->parts[self::WHERE]){
                
$this->_bind($stmt);
            }
            
$stmt->execute();
            
$result $stmt->fetchAll();
        }catch(
PDOException $e){
            throw new 
dGroup_Exception($e->getMessage());
        }
        
        return 
$result;
    }
 }
?>
Uso PDO .
Aun le falta muchisimo por hacer.

Última edición por bulter; 02/01/2008 a las 09:55