This method is the most resource intensive, since it dynamically generates the class file that will interface with a database table. In general terms, the class file is built by concatenating strings, so the generation process shouldn't present any difficulties to being understood. First, the method obtains the field names of the table passed to the class, assigning them directly as class properties, storing temporarily the output in the $methods variable, to be included at a later time. The lines below perform these operations: // build class header $str='<?php class '.$this->name.'{'; if(!$result=mysql_query("SHOW COLUMNS FROM $this->table")){ die('Could not run query '.mysql_error()); } // build data member declaration if(mysql_num_rows($result)>0){ while($row=mysql_fetch_array($result,MYSQL_ASSOC)){ $str.='var $'.$row['Field'].'=\'\';'; $methods.='function set'.$row['Field'].'($'.$row['Field'].') $methods.='function get'.$row['Field'].'(){return $this- // store field names in array $fields[]=$row['Field']; } } Then, the class constructor is generated with this single line: $str.='function '.$this->name.'(){}'; Finally, the accessors and modifiers methods are appended to the output, like this: // build modifiers and accessors $str.=$methods; The next step is to append the "load()" and "submit()" methods to the output string, accomplishing the "SELECT" and "INSERT" single-row operations. They're defined as listed below: // build load() method $str.='function load(){$r=mysql_query("SELECT * FROM $str.='return mysql_fetch_array($r,MYSQL_ASSOC);}'; // build submit() method $str.='function submit(){mysql_query("INSERT INTO '.$this- foreach($fields as $field){ $str.=($field!='id')?$field.'=\'$this->'.$field.'\',':''; } $str.='");$this->id=mysql_insert_id();'; $str=preg_replace("/,\"/","\"",$str).'}'; Notice that in this case, we're using the native MySQL functions to execute queries and retrieve a row. However, this condition might be easily changed by utilizing methods provided by another object. So far, so good. We've already described the two main methods used to retrieve and insert a row into the database table. Our next task is to explain the remaining methods, "update()" and "delete()". Don't you worry, because they're just a few lines away.
blog comments powered by Disqus |
|
|
|
|
|
|
|