I have a NoteEntity
class that is meant to represent a row in my notes
table. An "(data)entity" in my framework strictly means a stored/storable data entry - a database row, if you will. Creating such an object is as straightforward as initializing it with an array returned by mysqli_fetch_array()
, which requires me to match the object properties to the column names of my table.
The constructor inherited from the parent DataEntity
class:
PHP code
public function __construct($row_array)
{
foreach ($row_array as $column => $value)
{
if (property_exists($this, $column))
{
$this->$column = $value;
}
else
{
trigger_error(get_class($this) . " has no attribute called '$column'.", E_USER_NOTICE);
}
}
}
As you can see, all it does is mapping the corresponding columns to their corresponding object properties.
This is fine for me, since the NoteEntity
class is defined only once, and thus it is easy to change its internal workings if the table columns would ever change. But this also requires me to use a getter method for each and every property, if I don't want my entire code to depend on the given table's column names.
Question goes as: is it good practice to have a getter for every property, or should I investigate another approach? I'm asking this from a performance perspective, but I'd wish to keep my code as maintainable as possible, as well.
The reason I'm concerned about performance is that if it gets a bit busier, getting the properties quickly becomes:
PHP code
foreach ($notes as $note_entity)
{
$template->Process(array(
'note_name' => $note_entity->GetName(),
'note_ext' => array_pop(explode('.', $note_entity->GetFilename())),
'subject_id' => $note_entity->GetSubjectID(),
'subject_name' => $note_entity->GetSubject(),
'institute_id' => $note_entity->GetInstituteID(),
'institute_nick' => $note_entity->GetInstitute(),
// ...
));
}
... which might be fine for a few dozen notes, but their count is anticipated to be in even the thousands per request, which adds significant function call overhead. The present version is extremely convenient to use, becase in no part of the code you need to keep the column names in mind.
Possible solutions that I came up with include an approach that returns every, or a subset of every property in an associative array. This has the following minor downsides:
- returning only a subset of data creates implicit logical dependencies between
NoteEntity
and where it is used, if the wanted subset is varying between calling locations, - returning all properties creates an unnecessary flow of data that will never be used,
- updating the colum configuration increases the cost of maintainibility, since we need to update the structure of the returned array as well.