A simple ORM can be built using __get()
and __set()
and a couple of custom methods (possibly using __call()
), here is a simple pseudo-code:
class ORM
{
private $table = null;
private $fields = array();
function __construct($table)
{
$this->table = $table;
}
function __get($key)
{
return isset($this->fields[$key]) ? $this->fields[$key] : false;
}
function __set($key, $value)
{
$this->fields[$key] = $value;
}
function load($id, $field = 'id')
{
// populate $this->fields with SELECT * FROM $this->table WHERE $field = $id;
}
function save()
{
if (isset($this->fields['id']))
{
// UPDATE $this->table SET $this->fields;
}
else
{
// INSERT INTO $this->table $this->fields;
}
}
}
$user = new ORM('user');
$user->name = 'name';
$user->pass = '1337';
$user->save();
This is just a basic example to get you started. You could add further logic using the __call()
magic method to fetch results by other fields than id
for instance.
Bear in mind that the example I gave doesn't handle relations, that's where various ORM implementations really differ, however I normally don't trust any ORM to handle relations for me since they tend to be way slower and not produce efficient queries.