From Genitura
<?php
/** model.php
* Create general structure for typical database interaction
*
* @author Julien Halle, Vincent Menard
* @version Genitura 0.1.1
*/
Class Model {
var $dbh;
function __construct() {
$this->dbh = new SQL_Class();
}
final public function save(){
if ( $this->data['id'] == "" ) {
$this->insert();
} else {
$this->update();
}
}
function get_table(){
return get_class($this);
}
public function load($id, $deep = 0){
if ($id != '') {
$this->data['id'] = addslashes($id);
$sqlQuery = "SELECT * FROM ".$this->get_table()."
WHERE id=".$this->data['id']." LIMIT 1";
$sql = $this->dbh->execute($sqlQuery);
$arr = $sql->fetch_assoc();
$this->array_to_object($arr,$deep);
}
}
function insert() {
$str = "INSERT INTO ".$this->get_table()." SET ";
foreach( $this->data as $key=>$val ) {
if (!is_object($val) && !is_array($val) && $val!='' )
$str .= "$key='$val', ";
}
$str = substr($str,0,-2);
$this->dbh->execute($str);
$id = $this->dbh->execute('SELECT LAST_INSERT_ID()');
list($id) = $id->fetch_array();
$this->data['id']=$id;
}
function update() {
$str = "UPDATE ".$this->get_table()." SET ";
foreach( $this->data as $key=>$val ) {
if (!is_object($val) && !is_array($val))
$str .= "$key='".addslashes(htmlentities($val))."', ";
}
$str = substr($str,0,-2);
$str .= " WHERE id = ".$this->data['id'];
//echo $str;
$this->dbh->execute($str);
}
public function all(){
$sql = $this->dbh->execute("SELECT * FROM ".$this->get_table().' '.$this->order.' '.$this->limit);
$list = Array();
while($row = $sql->fetch_assoc()){
$class = $this->get_table();
$obj = new $class;
$list[] = $obj->array_to_object($row);
}
return $list;
}
public function array_to_object($arr, $deep=0) {
foreach( $this->data as $key=>$val ){
if(isset($arr[$key])){
$this->data[$key] = $arr[$key];
} else if ($deep && is_array($this->data[$key])) {
$child = new $key;
$method = $this->get_class();
$method = 'load_by_'.$method.'_id';
$child->$method($arr['id'],$deep-1);
}
}
return $this;
}
public function get($param) {
return $this->data[$param];
}
public function set($param, $value) {
if ( isset($this->data[$param]) ) {
$this->data[$param] = $value;
} else {
die('Invalid call to method set($param,$value). param doesn\'t exist');
}
}
public function set_limit($offset, $limit) {
if (is_numeric($limit) && is_numeric($offset)) {
$this->limit = ' LIMIT '.$offset.', '.$limit;
} else {
die('Invalid call to method set_limit($int, $int)');
}
}
public function set_order($field) {
$this->order = ' ORDER BY '.$field;
}
}
?>