Re: [PHP-PEAR] Addition to DB/common.php ?

[email protected] (Kendrick Vargas)
Newsgroups php.pear
Message-ID <[email protected]>
On Fri, 2 Feb 2001, Chuck Hagenbuch wrote:

> Quoting Kendrick Vargas <[email protected]>:
>
> > Actually, I'd writting a class some time ago to do this. I'd been meaning
> > Would there be any use for that here? Would anyone want me to post it? I
> > have no formal education in programming, so I guess I'd be a little
> > nervous about having experienced people poking and prodding at my stuff,
> > but if it's useful I'd love to post it and have it included.
>
> If you're willing to post the code, post the code. :) It sounds interesting -
> although again, not something that should be in the core DB or DB_common
> classes - and if there's interest in it, I'm sure someone will volunteer to
> convert it.

Well, here goes... :-)

I call it my Data_Container. I usually extend it like so:

class Domain_Info extends Data_Container {

   var $table_name = "dns_zones";
   var $id_name = "zone_id";
   var $db = "";

   function Domain_Info ($id = "") {
      $this->db = new DB_Connection("temp_auth");

      if ( $this->Container_Init($id) ) {
         return(true);
      } else {
         return(false);
      }

   }

}

I try to return true or false on just about everything. And if I return
false, I try to set the internal $Error variable. Anyways... Feel free
			-peace

--- BEGIN GEEK CODE BLOCK ----------+----------
GAT d- s:+ !a C++$ UL/S/I/B++++$ P+ | "In the ongoing battle between objects
L++ E- W+(+++) N K-  w(---)  O-- M@ |  made of aluminum  going hundreds of
V(--) PS+++  PE Y+ PGP@ t++ 5 X+ R- |  miles per hour and the ground going
tv+ b- DI++++  D+(+++) G  e>++ h--- |  zero,  the  ground has yet  to lose."
r++ z+>+++ - END GEEK CODE BLOCK ---+
Data_Container.inc (text/plain, 11.9 KB)
<?PHP

/*
 * GO International, Inc.
 * Copyright (C) 2001 Kendrick Vargas
 * 
 * This library 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 2.1 of the License, or (at your option) any later version.
 * 
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

class Data_Container {
   # This class needs to be extended. It's too generic to live
   # on it's own. It needs a $db to be set (a PHPLib db object)
   # and a couple of other variables:
   #
   #    $id_name         The column name of the table index.
   #    $table_name      The name of the table to use.
   #
   # The $new_entry variable controls whether we're updating or
   # inserting. It's set to false when the container successfully
   # initiallizes to an entry in the db.

   var $id_name    = "";
   var $table_name = "";
   var $new_entry  = true;

   # CAUTION!!!
   # The $do_not_edit variable is an array of fields that should
   # not be touched when inserted into the database. Furthermore,
   # where a normal insert would do:
   #        $field='$value'
   # $do_not_edit assumes you've allready added the "'" character
   # to the end. I.e...
   #        $field=$value
   # Use with care....

   var $do_not_edit = array();

   # The following variables let you add raw suffixes to the
   # various queries. The variable $use_select_suffix_on_all
   # allows you to use the select suffix for the update and
   # delete suffixes as well.
   var $use_select_suffix_on_all = true;
   var $query_select_raw_suffix  = "";
   var $query_update_raw_suffix  = "";
   var $query_delete_raw_suffix  = "";


   # These are Pre/Post insertion/update/delete functions. Do not
   # enable these unless you have PHP 4.0RC1 or better.
   #
   # For each type (preif, postif, preuf, etc...), a funtion named
   # type_ is always executed. Then, a function named type_field
   # is called where field is the field name of the current data
   # value.
   var $enable_preif  = false;
   var $enable_postif = false;
   var $enable_preuf  = false;
   var $enable_postuf = false;
   var $enable_predf  = false;
   var $enable_postdf = false;

   # Variable checking functions. Use these functions to check out
   # and/or modify variables before inserting/updating.
   var $enable_vcf    = false;

   var $db    = "";
   var $Error = "";

   var $data        = array();
   var $classname   = "";
   var $audit_table = array();

   function Container_Init ( $id = "" ) {
      $this->classname = get_class($this);
      $id_name         = $this->id_name;
      $table_name      = $this->table_name;

      if ( $id != "" ) {
         $query="SELECT * FROM $table_name WHERE $id_name='$id' " . $this->query_select_raw_suffix;

         if ( $this->db->query($query) ) {
            $this->db->next_record();
            $this->data        = $this->db->Record;
            $this->audit_table = array();
            $this->new_entry   = false;
         } else {
            $this->Error  = "Container_Init(): A database error occured.\n";
            $this->Error .= "db->Query: ". $query ."\n";
            $this->Error .= "db->Error: ". $this->db->Error ."\n";
            $this->Error .= "db->Errno: ". $this->db->Errno ."\n";
            return(false);
         }
      } else {
         return(false);
      }

      if ( $this->db->nf() == 1 ) {

         # All systems go, now we check for an init helper
         # function. If it's not there, simply return true.
         # If it's there, run it and check it's return value.
         if ( method_exists($this, "init_helper") ) {
            return( ! eval("\$this->init_helper();") );
         } else {
            return(true);
         }

      } else if ($this->db->nf() > 1) {
         $this->Error = "Container_Init(): There was more than one return.";
         return(false);
      } else if ($this->db->nf() == 0 ) {
         $this->Error = "Container_Init(): There was no match for the specified entry in the database.";
         $this->new_entry = true;
         return(false);
      } else {
         $this->Error = "Container_Init(): There was a strange error, contact your administrator.";
         return(false);
      }

      # If we've gotten this far and haven't hit a successful
      # return, then return(false)... something must've gone wrong.      
      return(false);

   }

   function delete_entry () {
      $id_name = $this->id_name;
      $table_name = $this->table_name;

      # If we're a new entry, we don't need to delete ourselves.
      # Just go ahead and reset all the data.
      if ( $this->new_entry ) {
         $this->data        = array();
         $this->audit_table = array();
         $this->Error       = "";
         return(true);
      }


      # Handle our pre-deletion functions...
      if ( $this->enable_predf && (! $this->execute_all_sanity_functions("", "predf")) ) {
         return(false);
      }

      $query = "DELETE FROM $table_name WHERE $id_name='". $this->data[$id_name] ."'";

      if ( $this->use_select_suffix_on_all ) {
         $query .= " " . $this->query_select_raw_suffix;
      } else {
         $query .= " " . $this->query_delete_raw_suffix;
      }

      if ($this->db->query($query)) {
         $this->data        = array();
         $this->audit_table = array();
         $this->Error       = "";

         # Handle our post-deletion functions...
         if ( $this->enable_postdf && (! $this->execute_all_sanity_functions("", "postdf")) ) {
            return(false);
         } else {
            return(true);
         }

      } else {
         $this->Error  = "delete_entry(): Could not remove the entry.\n";
         $this->Error .= "db->Query: ". $query ."\n";
         $this->Error .= "db->Error: ". $this->db->Error ."\n";
         $this->Error .= "db->Errno: ". $this->db->Errno ."\n";
         return(false);
      }

   }

   function execute_all_sanity_functions ($data = "", $type = "", $force = false) {
      $class_vars = get_class_vars($this->classname);

      if ( $class_vars["enable_" . $type] || $force) {

         if ( ! is_array($data) ) {
            $data = &$this->data;
         }

         reset($data);
         $field = "";
         $value = "";
         do {
            if ( method_exists($this, $type . "_" . $field) ) {
               $my_var = "\$this->{$type}_{$field}(\"{$value}\");";
               if ( eval("$my_var") ) {
                  return(false);
               }
            }
         } while ( list($field, $value) = each($data) );

         return(true);

      } else {
         return(true);
      }

   }

   function f ($field) {
      return($this->data["$field"]);
   }

   function f_record () {
      return($this->data);
   }

   function set_field ($field, $value) {
      if ( $value != $this->data["$field"] ) {
         $this->data["$field"] = "$value";
         $this->audit_table["$field"] = true;
      }

      return(true);
   }

   function set_fields ($data) {
      while ( list($field, $value) = each($data) ) {
         if ( $value != $this->data["$field"] ) {
            $this->data["$field"] = $value;
            $this->audit_table["$field"] = true;
         }
      }
      return(true);
   }

   function reset_data ($id = 0) {
      $id_name = $this->id_name;

      if ( isset($this->data["$id_name"]) ) {
         $this->Container_Init($id);
      } else {
         $this->data = array();
         $this->audit_table = array();
      }

      return(true);
   }
 
   function set_all ($data) {
      $this->set_fields($data);
   }


   function commit_changes ($lock = false) {
      $id_name = $this->id_name;
      $table_name = $this->table_name;

      # First things first, we execute our variable checking
      # functions.
      if ( ! $this->execute_all_sanity_functions(&$this->data, "vcf") ) {
         return(false);
      }

      # There are two different query statements. If we are a new entry
      # then we need to construct an insert, otherwise we're updating.
      # In both cases, a loop is used to build the guts of the query
      # statement based on the actual data that's been set/modified.
      if ( $this->new_entry ) {

         $data = &$this->data;
         $query = "INSERT INTO $table_name SET ";

      } else {

         reset($this->data);

         # Here we build a local $data array of only the variables that
         # have changed using the $audit_table as a reference.
         reset($this->audit_table);
         $data = array();
         while ( list($field, $value) = each($this->audit_table) ) {
            if ($value) {
               $data["$field"] = $this->data["$field"];
            }
         }

         $query = "UPDATE $table_name SET ";

         # We're just updating information... disable locking.
         $lock = false;

      }

      # If we have no data to update, return now.
      if ( count($data) <= 0 ) {
         return(true);
      }

      # Build the guts of the SET.
      reset($data);
      while ( list($field, $name) = each($data) ) {
         if ( (! $this->do_not_edit["$field"]) || (! isset($this->do_not_edit["$field"])) ) {
            $query_set[] = "$field='". addslashes($name) ."'";
         } else {
            $query_set[] = "$field=$name";
         }
      }
      $query .= implode(",", $query_set);

      # Specify our index if we're updating. Add any additional arguments.
      if ( ! $this->new_entry ) {
         $query .= " WHERE $id_name='". $this->data["$id_name"] ."'";

         if ( $this->use_select_suffix_on_all ) {
            $query .= " " . eregi_replace("WHERE ", "AND ", $this->query_select_raw_suffix);
         } else {
            $query .= " " . eregi_replace("WHERE ", "AND ", $this->query_update_raw_suffix);
         }

      }

      # Handle our pre-insertion functions...
      if ( $this->new_entry ) {
         if ( ! $this->execute_all_sanity_functions(&$data, "preif") ) {
            return(false);
         }
      } else {
         if ( ! $this->execute_all_sanity_functions(&$data, "preuf") ) {
            return(false);
         }
      }


      # Run our query...
      if ( $this->db->query($query) ) {

         # If we're a new entry we try and get back our auto_incremented
         # id so that we can reinitiallize ourselves.
         if ( !isset($this->data["$id_name"]) ) {
            $this->db->query("SELECT LAST_INSERT_ID()");
            $this->db->next_record();
            $this->data["$id_name"] = current($this->db->Record);
         }

         # Handle our post-insertion functions...

         $data = $this->data;
         reset($data);
         if ( $this->new_entry ) {
            if ( ! $this->execute_all_sanity_functions(&$data, "postif") ) {
               return(false);
            }
         } else {
            if ( ! $this->execute_all_sanity_functions(&$data, "postuf") ) {
               return(false);
            }
         }

         return(true);            

      } else {
         $this->Error  = "commit_changes(): Could not update the entry.\n";
         $this->Error .= "db->Query: ". $query ."\n";
         $this->Error .= "db->Error: ". $this->db->Error ."\n";
         $this->Error .= "db->Errno: ". $this->db->Errno ."\n";
         return(false);
      }

   }

}

?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.