Hi,
I’m fairly new to Yii. I have a model class that overrides the __get() magic method to modify the value of an attribute retrieved from the database before it is returned by the class. This seems to work as expected. However, when I return the AR model as a JSON string the value of the attribute is not modified as expected. For example, the __get() override in the model class looks something like this:
class CustomContent extends CActiveRecord
{
…
public function __get($name)
{
if ($name == 'released')
{
// Always return the value of 'released' in lowercase.
return strtolower(parent::__get($name));
}// if
return parent::__get($name);
}
…
}
If, in the controller, I have code like this:
…
$ccAR = CustomContent::model()->find($criteria);
$rel = $ccAR->released;
…
The value of $rel is always lowercase, as expected.
But if I do the following:
…
echo CJSON::encode($ccAR);
…
The value of ‘released’ in the JSON string is as it came from the database - not always in lowercase. The __get() function is bypassed and never called.
Is this how this should work? I can get it to kinda work in the controller by the following code, but it should be in the model so the it is hidden from the controller.
…
$ccAR->released = $ccAR->released;
echo CJSON::encode($ccAR);
…
or I can add a function to the model class like:
…
public function jsonEncode()
{
$arr = $this->getAttributes();
foreach ($arr as $key => $value)
{
$arr[$key] = $this[$key];
}// foreach
return json_encode($arr);
}
…
Then, in the controller call this function instead of CJSON::encode() like:
…
echo $customContentAR->jsonEncode();
…
What is the better solution?
Thanks.