I’m working with a [generally not widely used] PHP framework in which the class I’m currently working with has an array of fields that correlate to columns in SQL.
Well, for setting values for class objects there’s a class method setFieldValue and conventionally something like this would be done:
protected $fields = array('id', 'name', 'body');
function setFieldValue($field, $value) {
switch($field) {
case 'id':
return parent::setFieldValue($field, intval($value));
case 'name':
return parent::setFieldValue($field, strval($value));
case 'body':
return parent::setFieldValue($field, strval($value));
}
}
I’m looking for something a bit more dynamic (and cleaner, as I’ll have many fields), maybe like:
protected $fields = array('id' => 'intval', 'name' => 'strval', 'body' => 'strval');
function setFieldValue($field, $value) {
if(array_key_exists($field, $this->fields)) {
return parent::setFieldValue($field, $fields[$field]($value));
}
}
Would anyone consider this alternative I’m suggesting bad practice and furthermore would anyone suggest other alternatives?
No, it looks good because the name of the fields aren’t promoted to the outside of that class in both cases – the
switchor thearray_key_exists. So this should not make any difference, because you solve it internally (privately) which is invisible.Run your unit-tests before and after the changes to see if everything went smoothly.