0

我有一个带有一些基本值的模型类,现在我想用计算的 ID 字段对其进行扩展。在我的系统中,我们为每个实体使用一个 ID,它包含实体的类型和数据库中的自动增量 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;
    }
}

我应该如何扩展我的模型以将此值作为模型的参数?

更新

乔恩回答得非常好,官方文档真的很有帮助。但是,有了这个解决方案,现在getCid只调用函数,当我独立调用它时。当我通过模型的getAttributes($model->safeAttributeNames)(或getAttributes(array('cid')))调用它时,我得到null$model->cid 的值并且getCid不调用该方法。(属性设置为安全)

4

1 回答 1

3

为什么不简单地使用只读属性?

private $_cid;

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

    return $this->_cid;
}

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

于 2013-06-13T09:12:15.313 回答