fatfree-core
fatfree-core copied to clipboard
Suggestion: onget/onset hooks
Hi,
this topic made me wondering if the framework couldn't provide an easy way to manipulate the data coming from or going to the database. Easier than overloading the get()
and set()
methods.
Hence this proposal to add onget
and onset
hooks:
// auto-hash passwords
$mapper->onset(function($key,&$val){
if ($key=='password')
$val=Bcrypt::instance()->hash($val);
});
// auto-serialize/unserialize array data
$mapper->onset(function($key,&$val){
if ($key=='data')
$val=serialize($val);
});
$mapper->onget(function($key,&$val){
if ($key=='data')
$val=unserialize($val);
});
Actually @ikkez has implemented something similar in Cortex.
What do you guys think?
If we consider that nobody would need to define a generic hook, it could even be simplified in:
// auto-hash passwords
$mapper->onset('password',function(&$val){
$val=Bcrypt::instance()->hash($val);
});
// auto-serialize/unserialize array data
$mapper->onset('data',function(&$val){
$val=serialize($val);
});
$mapper->onget('data',function(&$val){
$val=unserialize($val);
});
I'd manipulate the data only right before they are inserted into the db, not after setting a value in the model. In Your case this means the password cannot be recovered from the model while creating / altering it. You can use traits to make this more generic (e.g. same fieldnames = same hooks) or use some sort of register-function in constructors. so for me there is no need for this.
I don't need this either, and I think it should be up to the application to resolve using the mapper triggers. I use the beforeInsert/Update/Save triggers and then I can modify the data, and throw an exception when something doesn't validate properly.
I think that's up to the developer to decide if he wants to be able to manipulate the plain password or not. AFAIK, I consider the mapper as an exact copy of a database record. Therefore, I know that $user->password
is hashed. If I need to keep track of the plain password, I'll make a copy before passing it to the setter.