David wrote:
A number of you to understand my question, but I'm
disappointed that there were no earthshattering solutions
I had been overlooking.
If I am not mistaken, most of O/R mappers out there are
code generators, not runtime mappers. Which are you
interested in?
I want to be able to modify one of the objects attributes
and then simply execute something like object.save() or
maybe database.save(object) to have it automatically updated
in the database.
OK, here's a rough MySQL-only draft or a run-time mapper:
class Mapper {
var $host;
var $user;
var $password;
var $db;
var $table;
var $link;
var $data;
var $primaryKey;
var $error;
function Mapper($host, $user, $password, $db, $table) {
$this->link = mysql_connect($host, $user, $password);
if ($this->link == false) {
$this->error = mysql_error();
return false;
}
$db_selected = mysql_select_db($db, $this->link);
if (!$db_selected) {
$this->error = mysql_error();
}
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->db = $db;
$this->table = $table;
$this->error = false;
}
function setPrimaryKey($key = '') {
if ($key == '') {
// Run "SHOW CREATE TABLE {$this->table}" and set
// $this->primaryKey equal to the name of the
// primary key field or, absent that, any key
// field
} else {
$this->primaryKey = $key;
}
}
function populate($key) {
$query = "SELECT * FROM {$this->table} " .
"WHERE {$this->primaryKey} = '$key'";
$result = mysql_query($query);
if ($result == false) {
$this->error = mysql_error();
return false;
} else {
$this->data = mysql_fetch_assoc($result);
return true;
}
}
function save() {
$query = "UPDATE {$this->table} SET ";
$add_comma = false;
$where = '';
foreach ($this->data as $field=>$value) {
if ($add_comma) {
$query .= ", $field='$value'";
} else {
$query .= "$field='$value'";
$add_comma = true;
}
if (strtolower($field) == strtolower($this->primaryKey)) {
$where = " WHERE $field = $value";
}
}
if ($where == '') {
$this->error = 'No primary key found; ' .
'UPDATE will not be attempted.';
return false;
} else {
$query .= $where;
$result = mysql_query($query);
if ($result) {
return mysql_affected_rows();
} else {
$this->error = mysql_error();
return false;
}
}
}
}
Example of usage:
$myMapper = new Mapper('localhost', 'root', 'password',
'myDB', 'myTable');
if ($myMapper->error) {
die('Mapper Error: ' $myMapper->error);
}
$myMapper->setPrimaryKey('ID');
$myMapper->populate(942385);
$myMapper->data['description'] =
"New description for item {$myMapper->data[$myMapper->primaryKey]}";
$myMapper->save();
Cheers,
NC