【问题标题】:Extending Yii model with predefined value使用预定义值扩展 Yii 模型
【发布时间】:2013-06-13 09:05:01
【问题描述】:

我有一个带有一些基本值的模型类,现在我想用一个计算的 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;
    }
}

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

更新

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

【问题讨论】:

    标签: php model yii


    【解决方案1】:

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

    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 作为属性访问此值。

    【讨论】:

    • 我想让它像基本属性一样,就像来自数据库的内容一样。而且我不想每次都调用单独的函数。那会让我很痛苦:)
    • @Edifice:我不明白你在说什么。如果定义了这个函数,可以使用cidas if it were a property
    • @Edifice:请务必阅读该指南的全部,它非常有用,可以让您了解 Yii 希望您如何做事。根据我的经验,如果你不按照 Yii 的方式做事,你就不会玩得开心。
    • 当我使用getAttributes() 时,现在不会调用这个getCid。我在列表中得到这个值,但作为null。 (我在那里添加了一个休息时间,它甚至没有被调用)顺便说一句。我可以将此cid 称为$product->cid,它可以工作,非常感谢。
    • @Edifice: getAttributes 返回getAttributeNames 指定的属性,所以如果你想改变它,你必须覆盖getAttributeNames。但我不确定这是否是个好主意,因为您没有提出这将为您解决的真正问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    相关资源
    最近更新 更多