用预定义的值扩展Yii模型


Extending Yii model with predefined value

我有一个具有一些基本值的模型类,现在我想用计算ID字段扩展它。在我的系统中,我们为每个实体使用一个ID,它包含实体的类型和来自DB的自动增量ID。

我需要一个参数,现在叫它$cid(计算id),它是初始化时设置的。

我试图在init/model函数中设置它,但我得到Property "Product.cid" is not defined.异常。

我试着创建一个函数:

public function _cid($value = null) {
    if($value == null){
        return $this->cid;
    }else{
        $this->cid = $value;
        return $this->cid;
    }
}

我应该如何扩展我的模型,使这个值作为模型的参数?

Jon回答得很好,官方文档也很有帮助。但是,在这个解中,getCid函数只有在我单独调用它的时候才会被调用。当我通过模型的getAttributes($model->safeAttributeNames)(或getAttributes(array('cid')))调用它时,我得到null作为$model->cid的值,并且没有调用getCid方法。(属性设置为安全)

为什么不直接使用只读属性呢?

private $_cid;
public function getCid()
{
    if ($this->_cid) === null {
        // calculate the value here on demand
        $this->_cid = 'whatever';
    }
    return $this->_cid;
}

由于CComponent__get的实现,您可以将此值作为$model->cid的属性访问。