0

I have a model class with some basic values, and now I want to extend it with a calculated ID field. In my system we use an ID for every entity, that is containing the type of the entity and the auto-increment id from the DB.

I would need a parameter, call it now $cid (calculated id) that is setted when it initialized.

I've tried to set it in the init/model functions, but I get Property "Product.cid" is not defined. Exception.

And I've tried to create a function:

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

How should I extend my model to have this value as a parameter of the Model?

Update

Jon answered really well and the official docs are really helpful. But, with this solution, now the getCid function is only called, when I call it independently. When I call it via the model's getAttributes($model->safeAttributeNames) (or getAttributes(array('cid'))), I get null as the value of $model->cid and the getCid method is not called. (attribute is setted to be safe)

1 Answer 1

3

Why don't you simply use a read-only property?

private $_cid;

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

    return $this->_cid;
}

Thanks to the implementation of __get in CComponent, you can access this value as a property with $model->cid.

Sign up to request clarification or add additional context in comments.

5 Comments

I'd like to have it like the basic properties, like what is coming from the database. And I don't want to call the separate functions every time. That would be pain in my ass :)
@Edifice: I don't understand what you are talking about. If you define this function, you can use cid as if it were a property.
@Edifice: Be sure to read all of that guide, it's very useful and will give you an idea of how Yii wants you to do things. In my experience, if you don't do things Yii's way you won't be having a good time.
Now this getCid is not called, when I use getAttributes(). I get this value in the list, but as null. (I added a break there and it's not even called) btw. I can call this cid as $product->cid and it works, so thanks for that.
@Edifice: getAttributes returns the attributes that getAttributeNames specifies, so if you want to change that you will have to override getAttributeNames. But I 'm not sure if that's a good idea because you have not presented the real problem that this is going to solve for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.