<?
/** -------------------------------------------------------------------------------------*
* Version: 1.0 *
* License: http://phpwebpad.hafij.com @copyright from 2010 *
* ---------------------------------------------------------------------------------------*
* DEVELOPED BY *
* Mohammad Hafijur Rahman (Badal) *
* hide@address.com, hide@address.com *
* ------------------------------------------------------------------------------------ **/
/**
* Any model class must extedn this Model class.
*/
abstract class Model {
private $tableDefinition = null;
private $info = array();
/**
* construct the model and call the table definition to be loaded.
*/
public function __construct() {
$this->tableDefinition = $this->getTableDefinition();
$this->loadTableDefinition();
}
/**
* Abstruct function must be implement by the child class.
*/
abstract function getTableDefinition();
/**
* Load the table definition to creat or alter the table automatically
*/
private function loadTableDefinition() {
$table = $this->tableDefinition;
if($table == null)
throw new Exception('Can not load table definition.');
if(Database::getCreateTableMode())
Database::createTable($table);
}
/**
* Magic __get return a property value
* @param string $name
* @return mixed
*/
public function __get($name) {
$pk = $this->tableDefinition->getPrimaryKeyName();
if($pk == $name) {
if(isset($this->info[$name]))
return $this->info[$name];
return null;
}
$value = null;
$flag = true;
foreach($this->info as $key => $val) {
if($key == $name) {
$value = $val;
$flag = false;
break;
}
}
if($flag)
throw new Exception(get_class($this)." does not have property ".$name);
return $value;
}
/**
* Magic __set. Set a property value.
* @param string $name
* @param mixed $value
*/
public function __set($name, $value) {
$pk = $this->tableDefinition->getPrimaryKeyName();
if($pk == $name) {
throw new Exception('Primary key can not be set from property.');
}
$columns = $this->tableDefinition->getColumns();
$flag = true;
foreach($columns as $c) {
if($c['name'] == $name) {
$this->info[$name] = $value;
$flag = false;
break;
}
}
if($flag)
throw new Exception(get_class($this)." does not have property ".$name);
}
/**
* Only Database will use this function.
* Never try from anywhere else. I said never.
*/
public function setPrimaryKey($value) {
if(empty($value))
throw new Exception('Primary key value can not be empty');
$this->info[$this->tableDefinition->getPrimaryKeyName()] = $value;
}
/**
* Retrun all the property of the model object.
* @return array
*/
public function getAllProperties() {
return $this->info;
}
}
?>