I’m writing a lightweight ORM that can map database columns to instance fields with different names
eg.
Database
- userid
- username
- anotherpoorlynamedfield
Object
- user_id
- username
- another_poorly_named_field
To do this my original design was something like this
abstract class DbObj {
/* In a subclass the author would provide the mapping of fileds
* from the database to the object
* e.g.
* array('userid' => 'user_id', 'username' => 'username'....
*/
protected static $db_to_obj = array();
/* This would be auto popuplated from $db_to_obj in reverse */
protected static $obj_to_db = array();
/* Many Methods truncated... */
/* Used by magic methods to make sure a field is legit */
public function isValidField($name) {
return in_array(strtolower($name), self::$db_to_obj);
}
}
Then I subclass this out
class Cat extends DbObj {
protected static $db_to_obj = array(
'catsname' => 'name',
'itsage' => 'age'
);
}
The isValidField method does not work as expected. Using a debugger or a good ol fashioned var_dump you will find that the value of self::$db_to_obj is that of the parent class. I would understand this if isValidField was static, but it is not. It does have a $this pointer and it does know its class.
Is there a workaround for this behaviour or a better architecture to use?
Here’s a solution: