当使用getAttributes时,组件属性没有调用get


Yii component property not calling get, when using getAttributes

我有一个具有Component属性的模型。当我初始化/获取这个模型(有一个生成它的函数)时,每次都应该预先计算这个值。

我将这个'默认值'放入属性的getter中:

public function getCid(){
    if ($this->_cid == null ){
        $this->_cid = generateCid();
    }
    return $this->_cid;
}

当我调用它时,它的get方法正常工作:

$model->cid; //returns good value

但是,当我试图用getAttributes()函数的其他参数获取它时,它不会调用它的get方法。

$model->getAttributes(array('cid')); //just to try only this property.

我不想欺骗数组与$model->cid独立获得它的值,并将其合并到getAttributes返回数组,因为我将有更多的属性在我的应用程序,我正在寻找一个快速的解决方案。

那么我应该把这个生成器移动到哪里,或者我应该做些什么来更容易地得到这个生成的id ?

更新:

我创建了一个基本的ActiveRecord类,这是扩展CActiveRecord,我添加了以下功能:

public function getAttributes($names=true){
    $base = parent::getAttributes($names);
    foreach($base as $key => $value)
        if(!$this->hasAttribute($key))
            $base[$key] = $this[$key];
    return $base;
}

这将调用每个添加的属性的get方法,所以它将更新它的内容。

您的实际模型是CActiveRecord模型吗?

根据CModel::getAttributes()的一部分显示的内容,根据您的模型类型将有不同的方法来处理此问题。

但是你最快的处理方法可能是在你的模型中覆盖getAttributes,并让它在你传入的数组中找到'cid'值时对你的getter进行自定义调用。

你可能想看看CActiveRecord::getAttributes()的想法,覆盖它,然后从您的自定义覆盖调用您的parent::getAttributes()