duanci3845 2013-06-13 19: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 20: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.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器