attributes = array(); $this->id = null; if($table) { $this->table = $table; } else { $this->table = strtolower(get_class($this)) . "s"; } } /** * Cannot be called statically, this is an instance method. Sets id and attributes to values in $arr * @return void * @param array $arr assoc array of attributes */ function fromArray( $arr ) { // should look for id and pop it out foreach( $arr as $i => $v ) { if( $i == 'id' ) { $this->id = $arr['id']; } else { $this->attributes[$i] = $v; } } } /** * @return array an associative array of fields=> values */ function toArray() { $arr = array(); foreach( $this->attributes as $key=>$value) { $arr[$key] = $value; } return $arr; } /** * @access public * @return int id of this record or null if record has not been saved yet */ function getID() { return $this->id; } function save() { if( is_null($this->id)){ return $this->insert(); } else { return $this->update(); } } function equals($object) { if(!is_subclass_of($object, 'ActiveRecord')) return FALSE; foreach($this->attributes as $i=>$v) { if($v != $object->get($i)) return FALSE; } return TRUE; } /** * Deletes record from DB, but does not null the object * @return bool true on success */ function delete() { $sql = "delete from $this->table where id=$this->id"; mysql_query($sql); return mysql_affected_rows() > 0; } function insert() { $columns = ''; $values = ''; $sql = "insert into $this->table set "; foreach( $this->attributes as $key=>$value) { $sql .= "$key='".mysql_real_escape_string($value)."', "; } $sql = rtrim($sql, ", "); if( !$res = mysql_query($sql)) { trigger_error( mysql_error() . __FILE__ . __LINE__ , E_USER_WARNING ); return FALSE; } if( !$this->id) { $this->id = mysql_insert_id(); } return TRUE; } function update() { $sql = "update $this->table set "; foreach( $this-> attributes as $key => $value ) { $sql .= "$key = '".mysql_real_escape_string($value)."',"; } $sql = rtrim($sql, ","); $sql .= " where id=$this->id"; if( !$res = mysql_query($sql)) { trigger_error( mysql_error(), E_USER_WARNING ); return FALSE; } return TRUE; } function get($attr) { if(isset($this->attributes[$attr])) { return $this->attributes[$attr]; } trigger_error("No such attribute"); return null; } /** * @param String $attr * @param mixed $value primitive or an object */ function set( $attr, $value ) { $this->attributes[$attr] = $value; } } ?>