In one of my models, I have added some public member variables that I then assign different values to based on calculations involving some of the values from the database columns.
I am able to access the value of these new variables in the model, but one thing is not working as I’d expected.
Most of the data I am working with are integers. In this same model, I created an afterFind() method that loops through the model’s attributes[] array and applies PHP’s number_format() function to each of the integer values it retrieves from MySQL.
The problem is that the public member variable I added does not receive formatting, because it does not appear in the model’s attributes[] array.
Is there some easier way to achieve what I’m trying to accomplish? I basically need to apply simple mathematical operations to the integer values from the database and assign them to the model’s member variables, which I can then access from the view. I am trying to avoid putting extra logic in my view files as much as possible.
Instead of using afterFind you may consider writing get methods.
For instance:
public function getSomeAttributeFormatted() {
return $this->format($this->someAttribute);
}
echo $model->someAttributeFormatted;
//OR you might consider
public function formatted($attribute) {
return $this->format($this->$attribute);
}
echo $model->formatted('someAttribute');