PhpMyObject
[ class tree: PhpMyObject ] [ index: PhpMyObject ] [ all elements ]

Source for file PMO_MyDbms.php

Documentation is available at PMO_MyDbms.php

  1. <?php
  2. /**
  3.  * This file contains the PMO_MyDbms abstract class which implements
  4.  * a generic Dbms object.
  5.  *
  6.  * This file is part of the PhpMyObject project.
  7.  * 
  8.  * For questions, help, comments, discussion, etc., please join our
  9.  * forum at {@link http://www.developpez.net/forums/forumdisplay.php?f=770}
  10.  * or our mailing list at {@link http://groups.google.com/group/pmo-dev}.
  11.  *
  12.  * PhpMyObject is free software: you can redistribute it and/or modify
  13.  * it under the terms of the GNU General Public License as published by
  14.  * the Free Software Foundation, either version 3 of the License, or
  15.  * (at your option) any later version.
  16.  *
  17.  * This program is distributed in the hope that it will be useful,
  18.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.    See the
  20.  * GNU General Public License for more details.
  21.  *
  22.  * You should have received a copy of the GNU General Public License
  23.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  24.  *
  25.  * @package        PhpMyObject
  26.  * @subpackage PMO_Core
  27.  * @author        Nicolas Boiteux <nicolas_boiteux@yahoo.fr>
  28.  * @link            http://pmo.developpez.com/
  29.  * @since        PhpMyObject v0.1x
  30.  * @version        $Revision: $
  31.  * @copyright    Copyright (C) 2007-2008 Nicolas Boiteux
  32.  * @license        GPLv3 {@link http://www.gnu.org/licenses/gpl}
  33.  * @filesource
  34.  *
  35.  */ 
  36.  
  37. /** requires the interface */
  38. require_once(dirname(__FILE__).'/PMO_Dbms.php');
  39.  
  40. /**
  41.  * This class describe a generic Dbms object. It's a factory
  42.  * abstraction that permits to instanciate driver like mysql,
  43.  * postgresql, pdo etc ...
  44.  * 
  45.  * This class also implements generic methods used by all drivers
  46.  *
  47.  * @package        PhpMyObject
  48.  * @subpackage PMO_Core
  49.  */ 
  50. abstract class PMO_MyDbms implements PMO_Dbms {
  51.  
  52.     /**
  53.      * current PMO_Dbbms instance
  54.      *
  55.      * @var object 
  56.      */
  57.     protected static $INSTANCE;
  58.  
  59.     /**
  60.      * a PMO_Dbms object or a database resource link
  61.      *
  62.      * @var object|resource
  63.      */
  64.     protected $db;    
  65.  
  66.     /**
  67.      * holds the queries log
  68.      *
  69.      * @var array 
  70.      */
  71.     protected $log = array();
  72.     
  73.     /**
  74.      * returns a reference to the PMO_Dbms object
  75.      * If it does not already exists a new object is created and retained for future use
  76.      *
  77.      * if an PDO object is provided as parameter, it will be used and will replace any
  78.      * existing instance.
  79.      *
  80.      * This uses the singleton design pattern. To get the object, use code such as this:
  81.      *
  82.      * <code>
  83.      * // either returns an existing instance or creates a new one and returns it
  84.      * $db = PMO_MyDbms::factory();
  85.      *
  86.      * // use an already defined PDO instance
  87.      * $pdo = new PDO("sqlite:/hoem/user/db/mydatabase.db");
  88.      * $db = PMO_MyBbms::factory($pdo);
  89.      * 
  90.      * </code>
  91.      *
  92.      * @param object $object            a PDO object
  93.      * @return PMO_Dbms 
  94.      */
  95.     public static function factory(PDO $object NULL){
  96.             
  97.         if(isset($object)){
  98.             $driver $object->getAttribute(PDO::ATTR_DRIVER_NAME);
  99.  
  100.             switch($driver){
  101.                 case 'sqlite':
  102.                     require_once("PMO_Dbms_Sqlite.php");
  103.                     self::$INSTANCE new Pmo_Dbms_Sqlite($object);
  104.                     break;
  105.  
  106.                 default:
  107.                     require_once("PMO_Dbms_Pdo.php");
  108.                     self::$INSTANCE new PMO_Dbms_Pdo($object);
  109.                     break;
  110.             }
  111.             return self::$INSTANCE;
  112.         }    
  113.         
  114.         if(!isset(self::$INSTANCE)){    
  115.             $config PMO_MyConfig::factory();
  116.             $authdb array("driver"=>$config->get('PMO_MyDbms.DRIVER')
  117.                             "host"=>$config->get('PMO_MyDbms.HOST')
  118.                             "base"=>$config->get('PMO_MyDbms.BASE')
  119.                             "user"=>$config->get('PMO_MyDbms.USER')
  120.                             "pass"=>$config->get('PMO_MyDbms.PASS')
  121.                             "dsn"=>$config->get('PMO_MyDbms.DSN'),
  122.                             "pdodriver"=>$config->get('PMO_MyDbms.PDODRIVER'));
  123.             
  124.             switch($authdb['driver']){
  125.                 case 'mysql':
  126.                         require_once("PMO_Dbms_Mysql.php");
  127.                         self::$INSTANCE new Pmo_Dbms_Mysql();
  128.                         break;
  129.                         
  130.                 case 'mysqli':
  131.                         require_once("PMO_Dbms_Mysqli.php");
  132.                         self::$INSTANCE new Pmo_Dbms_Mysqli();
  133.                         break;                        
  134.                         
  135.                 case 'pgsql':
  136.                         require_once("PMO_Dbms_Pgsql.php");
  137.                         self::$INSTANCE new Pmo_Dbms_Pgsql();
  138.                         break;
  139.                         
  140.                 case 'pdo':
  141.                         switch($authdb['pdodriver']){
  142.                             case 'sqlite':
  143.                             require_once("PMO_Dbms_Sqlite.php");
  144.                             self::$INSTANCE new Pmo_Dbms_Sqlite();
  145.                             break;                            
  146.                             
  147.                             default:
  148.                             require_once("PMO_Dbms_Pdo.php");
  149.                             self::$INSTANCE new Pmo_Dbms_Pdo();
  150.                             break;
  151.                         }
  152.                         break;
  153.                         
  154.                 default:
  155.                         throw new Exception("Error: ".$authdb['driver']." is not a PMO supported driver");
  156.                         break;
  157.             }
  158.             self::$INSTANCE->connect($authdb);
  159.         }        
  160.         return self::$INSTANCE;
  161.     }
  162.  
  163.     /**
  164.      * kills the current PMO_Dbms object
  165.      */
  166.     public static function killInstance(){
  167.         self::$INSTANCE NULL;
  168.     }
  169.     
  170.     /**
  171.      * Returns the DB link or DB object
  172.      *
  173.      * @return PMO_Dbms|resource               the PMO_MyDbms or database link resouRCE
  174.      */    
  175.     public function getDb(){
  176.         return $this->db;
  177.     }
  178.  
  179.     /**
  180.      * Set the DB link or DB object
  181.      *
  182.      * @param object|resource$object        the PMO_MyDbms or database link resouRCE
  183.      */    
  184.     public function setDb($object){
  185.         $this->db = $object;
  186.     }
  187.  
  188.     /**
  189.      * sets the query verbose log
  190.      *
  191.      * @param string $log        text to log
  192.      * @return void 
  193.      */
  194.     public function setLog($log){
  195.         if(PMO_MyConfig::factory()->get('PMO_MyDbms.LOG'))
  196.             $this->log[date(PMO_MyConfig::factory()->get('PMO_MyDbms.LOG_FORMAT'))." ".$_SERVER['REMOTE_ADDR']." ".$log." ".$_SERVER['REQUEST_URI'];    
  197.     }
  198.     
  199.     /**
  200.      * retrieves thee query verbose log
  201.      *
  202.      * @return array 
  203.      */
  204.     public function getLog(){
  205.         if(isset($this->log))
  206.             return $this->log;
  207.         else
  208.             return FALSE;
  209.     }
  210.     
  211.     /**
  212.      * converts the attribute types from database to PHP primary types:
  213.      * string, float, or int
  214.      *
  215.      * @param string $type            the database type to convert
  216.      * @return string                    a PHP data type
  217.      */
  218.     protected function translateType($type){
  219.         if (eregi('int'$type)) {
  220.             return "int";
  221.         }
  222.         if (eregi('float'$type)) {
  223.             return "float";
  224.         }
  225.         if (eregi('blob'$type)) {
  226.             return "string";
  227.         }
  228.         if (eregi('text'$type)) {
  229.             return "string";
  230.         }
  231.         if (eregi('char'$type)) {
  232.             return "string";
  233.         }            
  234.         if (eregi('date'$type)) {
  235.             return "string";
  236.         }
  237.         if (eregi('time'$type)) {
  238.             return "string";
  239.         }
  240.         if (eregi('double'$type)) {
  241.             return "float";
  242.         }
  243.         return "string";
  244.     }
  245.  
  246.     /**
  247.      * Load a data row from the database and fills the PMO_Object with it
  248.      * 
  249.      * The data come from the first row of the fetchArray() method
  250.      * 
  251.      * @throws Exception
  252.      * @return void 
  253.      */
  254.     public function load(PMO_Object $object){
  255.         $whereclause "";
  256.         $objectAttributes $object->getObjectAttribute();
  257.         $objectTable $object->getTable();
  258.         
  259.         foreach ($objectAttributes as $column=>$value)
  260.             $whereclause .= " AND {$column}='{$value}'";
  261.  
  262.         $query "SELECT * FROM ".$objectTable->getTableName()." WHERE ".substr($whereclause5strlen($whereclause)).";";
  263.         $this->setLog($query);
  264.         $this->query($query);
  265.         $result $this->fetchArray();
  266.         
  267.         if(!$result)    
  268.             throw new Exception("Error: Object ".$objectTable->getTableName()." can not be found in database");
  269.             
  270.         $tablefields $objectTable->getColumns()
  271.         foreach$tablefields as $key=>$field){
  272.             $object->set($field$result[$field]);
  273.         }
  274.     }
  275.     
  276.     /**
  277.      * deletes the data row corresponding to the PMO_Object from the database table
  278.      * All primary key must be fill.
  279.      * 
  280.      * @param object $object        a PMO_Object corresponding to the target table
  281.      * @return bool                    TRUE if the insert went PL
  282.      * @throws Exception                if something went wrong
  283.      */
  284.     public function delete(PMO_Object $object){
  285.         $querypk "";
  286.         $objectattributes $object->getObjectAttribute();
  287.         $objectTable $object->getTable();
  288.         $tablepk $objectTable->getPk();
  289.             
  290.         foreach$tablepk as $pk){
  291.             if($objectTable->getPerm($pk!= "rw")
  292.                 throw new Exception("Error: primary key ".$pk." is not writable");
  293.  
  294.             if($objectattributes->offsetExists($pk))    
  295.                 $querypk .= " AND {$pk}='{$objectattributes->offsetGet($pk)}'";
  296.             else
  297.                 throw new Exception("Error: primary key ".$pk." is undefined");
  298.         }
  299.             
  300.             
  301.         $query "DELETE FROM {$objectTable->getTableName()} WHERE ".substr($querypk5strlen($querypk)).";";
  302.         $this->setLog($query);
  303.         $this->query($query);
  304.         return TRUE;
  305.     }
  306.     
  307.     /**
  308.      * updates the database table corresponding to the PMO_Object
  309.      * All primary keys must be fill.
  310.      *
  311.      * @param object $object        a PMO_Object corresponding to the target table
  312.      * @return bool                    TRUE if the insert went PL
  313.      * @throws Exception                if something went wrong
  314.      */    
  315.     public function update(PMO_Object $object){
  316.         $queryfield "";
  317.         $querypk "";
  318.         $objectAttributes $object->getObjectAttribute();
  319.         $objectTable $object->getTable();
  320.         $tablepk $objectTable->getPk();            
  321.         
  322.         foreach ($objectAttributes as $columns=>$value){                    
  323.             if($objectTable->isPk($columns)){
  324.                 if($objectTable->getPerm($columns!= "rw")
  325.                     throw new Exception("Error: primary key ".$columns." is not writable");
  326.                 
  327.                 $querypk .= " AND {$columns}='{$value}'";
  328.             }else{
  329.                 if($objectTable->getPerm($columns== "rw")
  330.                     $queryfield .= ",{$columns}='{$value}'";
  331.             }
  332.         }
  333.         
  334.         $query "UPDATE {$objectTable->getTableName()} SET ".substr($queryfield1strlen($queryfield))." WHERE ".substr($querypk5strlen($querypk)).";";
  335.         $this->setLog($query);
  336.         $this->query($query);
  337.         return TRUE;        
  338.     }
  339.     
  340.     /**
  341.      * inserts new data into the database table corresponding to the PMO_Object
  342.      * all primary keys must be fill.
  343.      * 
  344.      * @param object $object        a PMO_Object corresponding to the target table
  345.      * @return bool                    TRUE if the insert went PL
  346.      * @throws Exception                if something went wrong
  347.      */    
  348.     public function insert(PMO_Object $object){
  349.         $queryfield "";
  350.         $value "";
  351.         $objectAttributes $object->getObjectAttribute();
  352.         $objectTable $object->getTable();
  353.         $tablecolumns $objectTable->getColumns();
  354.         
  355.         foreach($tablecolumns as $field){
  356.                 if($objectAttributes->offsetExists($field)){
  357.                     if($objectTable->getPerm($field== "rw"){
  358.                         $queryfield .= ",{$field}";
  359.                         $value .= ",\"{$objectAttributes->offsetGet($field)}\"";
  360.                     }
  361.                 }
  362.         }
  363.         
  364.         $value substr($value1strlen($value));
  365.         $queryfield substr($queryfield1strlen($queryfield));
  366.         $query "INSERT INTO {$objectTable->getTableName()}($queryfield) VALUES($value);";
  367.         $this->setLog($query);
  368.         $this->query($query);
  369.         
  370.         $autoincrement $objectTable->getAutoincrement();
  371.         if(isset($autoincrement))
  372.             $object->set($autoincrement$this->getLastId());
  373.     
  374.         return TRUE;
  375.     }    
  376.  
  377.     
  378. }
  379. ?>

Documentation generated on Wed, 15 Oct 2008 09:17:10 -0400 by phpDocumentor 1.4.1