With PDO, we can now easily map our fields to an object's property, at a blazing speed. this:
$stmt = $db->prepare('SELECT foo,bar FROM table WHERE id=28');
$object = $stmt->fetch();
$object is now an object of class myClass with foo and bar as properties. neat!
Now, wouldn't it be incredible if I could save my object back in the database just with built-in functions from PDO or php, or even MySQL! something like this:
$stmt = $db->prepare('UPDATE table SET * = ?');
As of now, I define custom saving classes for each instance. While fast, this is a hassle for maintaining and very error-prone.
Of course, an object must have exactly the same properties as what it's trying to update, or maybe less fields, but not more.
does it exists? the lacking part of PDO as the perfect ORM?!
Best How To :
So I ended up using a very prominent feature of oop: destructors!
The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
which is very sweet, because what I want is to maintain the state of my objects between clicks on my website. This implies different things which I am not sure if they are good practice or not, but it is a bit error prone.
- The fields in the database and the object properties should be the same to simplify destructor code and make it more portable
- I'm using PDO's
FETCH_CLASS mode to build an object (as in the question)
now the interesting part is with the destructor, which can save back the properties to the relevant fields in the database:
$whitelist = array_flip(array('foo','bar'));
// I'm pretty sure not all my properties belong in my table
foreach (get_object_vars($this) as $key => $value)
if (!isset($whitelist[$key])) continue;
$fields = $key . '=?';
$values = $value;
$sql = 'UPDATE table SET ' . implode($fields) . 'WHERE id=?';
$values = $this->getId();
$stmt = $db->prepare($sql);
and there it is! next time I construct my object from the database, it is exactly the same as it was the last time it was accessed.