Minimalteck.fr
Accueil du site > Dév. Web > Classe Objet générique

Classe Objet générique

vendredi 31 octobre 2008, par Minimalteck

  Sommaire  

 La classe :

Classe abstraite pour créer/modifier/supprimer des objets construits à partir d’une base de données, ici mysql (Auto_increment) et utilisant PDO

<?php
require_once('DatabaseConnection.class.php');
abstract class GenericObject {

        protected $table;
        protected $fields;
        protected $primary_key;
        protected $id = NULL;
        private $data = array();
        private static $db;
        private $autoIncrement = true;
       
       
       
        public function __construct($id=NULL){
                $this->db = DatabaseConnection::get()->handle();
                if ( (!is_null($id)) && (is_numeric($id))) {
                        $this->id = $id;
                        $this->load();               
                }
        }
       
        public function __destruct(){

        }
       
        public function __set($key, $value) {
        $this->$key = $value;
   }
   

    function __get($key) {
        return $this->$key;
    }
   
   public function autoIncrement($bool){
           if(is_bool($bool)){
                        $this->autoIncrement = $bool;
           }
        }
   
        public function load() {
           $this->db = DatabaseConnection::get()->handle();
           $sql = 'SELECT '.implode(', ',$this->fields).' FROM `'. $this->table .'` WHERE ';
           $sql .=' `'.$this->primary_key.'` = "'.$this->id.'" LIMIT 1;';
           
            $sth = $this->db->query($sql);
            $result  = $sth->fetch(PDO::FETCH_ASSOC);
           if (is_array($result)) {
                   $this->data = $result;
           }
            unset($result);
   }
          
        public function save(){
                $this->db = DatabaseConnection::get()->handle();
               
                if(is_null($this->id) && $this->autoIncrement){//INSERT A NEW RECORD
                                $sql = 'SHOW TABLE STATUS LIKE "'.$this->table.'"';
                                $sth = $this->db->query($sql);
                                $row = $sth->fetch(PDO::FETCH_ASSOC);
                                $this->id= $row['Auto_increment'];
                                $sth->closeCursor();
                }
               
                $bind_array = array();
                $sql_stmt = 'REPLACE INTO ' .$this->table. ' SET';
                foreach($this->data as $field => $value) {
                        $bind_array[] = $this->db->quote($value);
                        $sql_stmt .= ' '.$field.' = ? ,';
                }
                $sql_stmt = substr($sql_stmt,0,-1);
               
                $stmt =  $this->db->prepare($sql_stmt);
                if (!$stmt) {
                   echo "\nPDO::errorInfo():\n";
                   print_r($this->db->errorInfo());
                } else {
                        if ($stmt->execute($bind_array) === false){
                                       $error = $this->db->errorInfo();
                                        print_r($error);
                                  die();
                                } else {
                                        return true;
                                }
                }
               
       
               
               
               
       
        }

       
        public function remove(){
                if (!is_null($this->id)) {
                        $this->db = DatabaseConnection::get()->handle();
                        $sql = 'DELETE FROM ' .$this->table. ' WHERE '.$this->primary_key.'=' . $this->id .';';
                        if (!$this->db->exec($sql)) {
                            $error = $this->db->errorInfo();
                                print_r($error);
                        } else {
                                return true;
                        }
                       
                }
        }
       
          
   public function getDatas(){
           return $this->data;
   }

   public function setDatas($assign_values){
           foreach ($assign_values as $key => $value) {
                   $this->data[$key] = $value;
           }
   }
   
}
?>

 Son utilisation :

Il suffit d’étendre la classe pour créé un nouvel objet, en affectant :
- la table de données ("$table") ;
- les valeurs des colonnes de cette table ("$fields") ;
- la clé primaire ("$primary_key").

Exemple :

<?php
require_once('GenericObject.class.php');
class Person extends GenericObject {
        protected $table = 'person';
        protected $fields = array('id_person',
                                                        'name',
                                                        'firstname',
                                                        'email');
        protected $primary_key = 'id_person';
}
?>
SPIP | squelette | | Plan du site | Suivre la vie du site RSS 2.0