I have a Model with a Component property. This value should be pre-calculated every time, when I initialize/get this Model (there is a function that generates it).
I placed this 'default value' into the getter of the property:
public function getCid(){
if ($this->_cid == null ){
$this->_cid = generateCid();
}
return $this->_cid;
}
When I call it, its get method is properly working:
$model->cid; //returns good value
But, when I try to get it with other parameters with getAttributes()
function, it doesn't call it's get method.
$model->getAttributes(array('cid')); //just to try only this property.
I don't want to trick with arrays to get it's value independently with $model->cid
and merge it into the getAttributes
return array, because I will have lot more properties in my app and I am looking for a fast solution.
So where should I move this generator, or what should I change to get this generated id easily?
Update:
I created a base ActiveRecord class, that is extending the CActiveRecord
and I added the following function:
public function getAttributes($names=true){
$base = parent::getAttributes($names);
foreach($base as $key => $value)
if(!$this->hasAttribute($key))
$base[$key] = $this[$key];
return $base;
}
This calls every added attribute's get method, so it will update it's content.
Is your actual model a CActiveRecord
model?
Based on what is shown as part of CModel::getAttributes(), there would be different ways to handle this depending on your model type.
But your quickest way to handle it would probably be to override getAttributes
in your model and have it do a custom call to your getter if the 'cid'
value is found in the array you pass in.
You'll probably want to look at CActiveRecord::getAttributes() for ideas, override it and then call your parent::getAttributes()
from your custom override.