Version: 1.0

Type: Class

Category: Databases

License: GNU General Public License

Description: Object that map a table row in the object world. - Create object from DB (using table and key). - Create an HTML fragment for read only display of read-write (form). - Re-create object from POST variables in the page called by the form. - Save object to DB.



<?php
/*
  ====================================================================
    Pierre WARGNIER - pierre.wargnier@laposte.net
  ====================================================================
    entity.inc
  ====================================================================
  ====================================================================
    2/7/2001 - version 1.0 Creation
  ====================================================================

  ENTITY CLASS
  ====================================================================
  The entity class is  a base class.  It  is  the mother of all  these
  objects that   have  to be  stored  into  the database.  Read method
  headers to see what it can do!

  Database interface:
  ------------------
  I  used a file called db_mysql.inc   (Session Management for PHP,(C)
  Copyright 1998  SH  Online   Dienst GmbH  Boris   Erdmann,  Kristian
  Koehntopp) that provides   me with a  $db  object 4 methods of  this
  object are used here. The  primary key of the table should be called
  "id".

  metadata(<X>): Returns   an   array  of  associative   arrays,  each
                 associative array represents  a column  in the  table
                 called <X>. With the "name" key  we have the name  of
                 the field.
  query(<X>):    Execute a SQL statement <X>.
  next_record(): Put a pointer on the next (first if called first) row
                 returned by a select query.
  f(<X>):        Returns the value  of  the field  named <X>  in   the
                 selected row

  usage
  -----
  Create the db object:
  
  require_once('db_mysql.php');

  class MYDBASE extends DB_Sql {
      var $Host     = '<host>';
      var $Database = '<base>';
      var $User     = '<user>';
      var $Password = '<password>';
  }
  $db = new MYDBASE;

  This class  can't be used directly,  it has to be  used in a derived
  class where you will define the table variable.

  class Object extends Entity {
    var $table = 'object';
    function Object($source,$id=''){
      $this->Entity($source,$id);
    }
  }

  If the page is a modification form:

  $obj = new Object('db','<a key>');
  echo '<form ...>';
  echo '<input type="hidden" name="id" value="<a key>"';
  echo $obj->form();
  echo '</form>';

  If the page is a page called by the form:

  $obj = new Object('form', $id);
  $obj->save();

*/

class Entity {
  var $id;		 // entity id = table key
  var $table;            // the table were the entity is stored

  /*
  constructor method
  --------------------------------------------------------------------
  This constructor create the object.  There are tree kind of object
  creation,  to choose one  just use blank,  db or form as the first
  parameter and the id as second (for blank id is not required):
  - creation of a new blanc object (blank)
  - recall of  an object stored in  base (db),
  - recall of an object transmited by a form (form)
  If a object cannot be recalled from a form or db, the table is set
  to '' (A way of saying that is a NULL entity).
  */
  function Entity($source,$id=''){
    if ($this->table == NULL) die('Can\'t instanciate virtual class Entity');
    $this->id = $id;
    global $db, $PREFIX;
    $this->table = $PREFIX.$this->table;
    //query the name of the properties
    $fields = array();
    $fields = $db->metadata($this->table);
    foreach ($fields as $field){
      $name = $field["name"];
      if ($name != 'id'){
	$this->{$name}='';
      }
    }

    //query values if we recall object from db
    if($source == 'db' and $id != NULL){
      $query = 'SELECT ';
      foreach (get_object_vars($this) as $key => $val){
	if($key != 'id' and $key != 'table'){
	  $query .= $key.',';
	}
      }
      $query = substr($query, 0, strlen($query) - 1);
      $query .= ' FROM '.$this->table;
      $query .= ' WHERE id=\''.$this->id.'\'';
      $db->query($query);
      if ($db->num_rows() == 1){
	if($db->next_record()){
	  foreach (get_object_vars($this) as $key => $val){
	    if($key != 'id' and $key != 'table'){
	      $this->{$key} = $db->f($key);
	    }
	  }
	}
      }else{
	$this->table ='';
      }
      //query values if we recall object from form 
    }elseif($source == 'form' and $id != NULL){
      if(!isset($GLOBALS[$this->table.'_'.$this->id])){
	$this->table ='';
      }else{
	foreach (get_object_vars($this) as $key => $val){
	  if($key != 'id' and $key != 'table'){
	    $temp = $GLOBALS[$this->table.'_'.$this->id.'_'.$key];
	    if (get_magic_quotes_gpc()){
	      $temp = stripslashes($temp);
	    }
	    $this->{$key} = $temp;
	  }
	}
      }
    }  
  }

  /*
  isNull method
  --------------------------------------------------------------------
  This method should be called each time an object is created with the
  db or form method to check if the id was valid.
  */
  function isNull(){
    if($this->table == '')
      return TRUE;
    return FALSE;
  }

  /*
  dump method
  --------------------------------------------------------------------
  This is a debug   only method. This  method  returns all the  values
  stored into an object in a  HTML fragment.
  */


  function dump(){
    $ret  = "<table>\n";
    $ret .= '<tr><th>id</th><td>'.htmlspecialchars($this->id,ENT_NOQUOTES)."</td></tr>\n";
    $ret .= '<tr><th>table</th><td>'.$this->table."</td></tr>\n";
    $ret .= '<tr><th>class</th><td>'.get_class($this)."</td></tr>\n";
 
    foreach(get_object_vars($this) as  $key => $value){
      if( $key  != 'id' and  $key != 'table'){
	$ret .= '<tr><th>'.$key.'</th><td>'.htmlspecialchars($value,ENT_NOQUOTES)."</td></tr>\n";
      }
    }
    $ret .= "</table>\n"; return $ret;
  }

   /*
  form method
  --------------------------------------------------------------------
  This returns HTML code of a fragment of  form that is used to modify
  the object.  Variables we be called <table>_<id>_<field name>. There
  is a variable <table>_<id> that contains the name of the class.

  */
  function form(){
    $ret  = "<table>\n";
    $ret .= '<tr><th>id</th><td>'.htmlspecialchars($this->id,ENT_NOQUOTES)."</td></tr>\n";
    $ret .= '<tr><th>class</th><td><input type="hidden" name="'.$this->table.'_'.htmlspecialchars($this->id,ENT_QUOTES).'" value="'.get_class($this).'">'.get_class($this)."</td></tr>\n";
    $ret .= '<tr><th>table</th><td>'.$this->table."</td></tr>\n";
    foreach(get_object_vars($this) as $key => $value){
      if($key != 'id' and $key != 'table'){
	$ret .= '<tr><th>'.$key.'</th><td><input type="text" name="'.$this->table.'_'.htmlspecialchars($this->id,ENT_QUOTES).'_'.$key.'" value="'.htmlspecialchars($value,ENT_QUOTES).'"></td></tr>'."\n";
      }     
    }
    $ret .= "</table>\n";
    return $ret;
  }

  /*
  script method
  --------------------------------------------------------------------
  This method returns  the   Javascripts statements that has  to  be
  inserted into a SCRIPT element.
  */
  function script(){
    return TRUE;
  }

  /*
  display method
  --------------------------------------------------------------------
  This returns HTML code  used to display the object to the user. Now
  it just call dump, but you can build a more fancy display.
  */
  function display(){
    return $this->dump();
  }

  /*
  save method
  --------------------------------------------------------------------
  This method  store   (create   or  update)   the   object into   the
  database. If the object id property was  not defined, the method put
  the key used to store the object into the table. Return TRUE in case
  of success.
  */
  function save(){
    global $db;
    $this->delete();
    foreach (get_object_vars($this) as $key => $val){
      if( $key != 'type' and $key != 'table'){
	$keys .= $key.',';
	$vals .= '\''.addslashes($val).'\',';
      }
    }
    $keys = ' ('.substr($keys, 0, strlen($keys) - 1).') ';
    $vals = ' ('.substr($vals, 0, strlen($vals) - 1).') ';
    $query = 'INSERT INTO '.$this->table.$keys.'VALUES'.$vals;
    return($db->query($query));
  }

  /*  
  delete method
  --------------------------------------------------------------------
  Delete object from the database. Return TRUE if success.
  */
  function delete(){
    global $db;
    if( $this->id != '' ){
      return($db->query("DELETE FROM $this->table WHERE id='$this->id'"));
    }
  }
}
?>