I think using Reflection is a bit overkill.
You can simple cast an object to an array to get all its attributes. Its just a matter of filtering, and rekeying that array to turn it into something you can use with PDO.
PHP Code:
<?php
class TinyObjectMapper
{
protected $className;
protected $mapOut;
function __construct($className, $mapOut) { $this->className = $className; $this->mapOut = $mapOut; }
function getClassName() { return $this->className; }
function mapOut($object)
{
$array = (array)$object;
return array_combine($this->mapOut, array_intersect_key($array, $this->mapOut));
}
function mapIn($row)
{
$r = array();
foreach($this->mapOut as $propertyName => $columnName)
$r[substr($propertyName, 3)] = $row[$columnName];
return call_user_func(array($this->className, '__set_state'), $r);
}
}
class Person
{
protected $id;
protected $firstName;
protected $lastName;
function __construct($firstName, $lastName, $id = null)
{
$this->id = $id;
$this->firstName = $firstName;
$this->lastName = $lastName;
}
static function __set_state(array $values)
{
return new self($values['firstName'], $values['lastName'], $values['id']);
}
}
class PersonMapper extends TinyObjectMapper
{
function __construct($className = 'Person', array $mapOut = array())
{
$mapOut["\0*\0id"] = 'p_ID';
$mapOut["\0*\0firstName"] = 'p_FirstName';
$mapOut["\0*\0lastName"] = 'p_LastName';
parent::__construct($className, $mapOut);
}
}
$personMapper = new PersonMapper();
$homer = new Person('Homer', 'Simpson');
var_dump($personMapper->mapOut($homer));
$homer = $personMapper->mapIn(array('p_ID' => 1, 'p_FirstName' => 'Homer', 'p_LastName' => 'Simpson'));
var_dump($homer);
Bookmarks