I've been suggested to use Mappers to separate object storage in db from real object behaviour, which sounds like a nice idea. But being used to other OOP languages like Java or SmallTalk, I always try to encapsulate my objects the most I can. I've read several mappers examples and some of them access the variables of the domain object directly (which would be my last choice, though I know it's more comfortable).
The only solution I currently come up with is something like:
class User{
public __construct($mapped_data){
foreach($data as $key=>$value){
$this->$key=$value;
}
...
}
class UserMapper{
private populate($user,$db_data){
...
$map=array('id'=>'id','psw'=>'password','mail'=>'email', ...);
foreach($db_data as $key=>$value){
$mapped_data[$map[$key]]=$value;
}
return new User($mapped_data);
}
}
The map is because the class User doesn't have to know the db column names at all.
Is this approach correct? Is there a better one? Thanks