duanci3845 2013-06-13 11:00
浏览 276
已采纳

使用getAttributes时,Yii组件属性不调用get

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.

  • 写回答

1条回答 默认 最新

  • dongqiang2069 2013-06-13 12:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部