Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables - Updating and deleting a row: the "update()" and "delete()" methods (
Page 5 of 6 )
Not surprisingly, these two methods are self-explanatory. They accomplish the tasks of updating and deleting a row from a table, using regular DML statements. Their definitions look like this:
// build update() method
$str.='function update(){mysql_query("UPDATE '.$this-
>table.' SET ';
foreach($fields as $field){
$str.=($field!='id')?$field.'=\'$this->'.$field.'\',':'';
}
$str=preg_replace("/,$/","",$str);
$str.=' WHERE id=\'$this->id\'");}';
// build delete() method
$str.='function delete(){mysql_query("DELETE FROM '.$this-
>table.' WHERE id=\'$this->id\'");}';
The above lines append the methods to the progressive output, for providing the DB interface class with the ability to update and delete a row. As you might guess, building the class is just a matter of concatenating simple strings.
Once the complete class code has being generated, we need to write it to a file, so the class file will be automatically created for spawning data access objects, and tying these objects to each related database table. The lines below create the specified class file at the given path:
// write class code to file
$fp=fopen($this->path.$this->name.'.php','w') or die('Failed
opening file');
fwrite($fp,$str);
fclose($fp);
// delete temporary variables
unset($fp,$str,$row,$fields,$field);
Lastly, in order to make the class behave as an "object factory", we define the "getObject()" method, which includes the DB interface file and returns a new object for usage within the application:
function getObject(){
// check if class file exists
if(file_exists($this->path.$this->name.'.php')){
require_once($this->path.$this->name.'.php');
// create object
return new $this->name;
}
return false;
}
Although the class definition is certainly quite simple, it reveals its real strength when used in conjunction with multiple DB interfaces, allowing more flexible and efficient database table manipulation.
However, by now we'll see how the class can be implemented in a rather basic way, so we're able to spot the main differences compared to the version presented in the previous article. Thus, in the next lines, we'll see the a brief example for proper class usage.