robsch
robsch

Reputation: 9728

Yii2: How to make an attribute of an ActiveRecord object read-only from the outside?

I would like to ask this in general. But I think the BlameableBehavior and the TimestampBevavior could be good examples where this is needed:

What would I have to do so that an attribute can only be read but not modified from the outside of an ActiveRecord object? In certain cases it should be modified internally, like it is required by the mentioned Behaviors. But never from the outside. How can this be achived? With validation rules? With overridden setters? Reverting attributes on update events?

Example

This should work as expected, since it is part of the class and is considered as 'internal':

/**
 * @property integer $created_by
 * @property integer $updated_by
 */
class Item extends ActiveRecord {

    public function behaviors() {
        return [
            [
                'class'              => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
        ];
    }
}

This shouldn't be possible. How ever it gets accomplised:

$item->created_by = $user->id;
$item->save();

At least it shouldn't have any effect.

This example uses the Behavior, but it can be thought for any other attribute.

Upvotes: 3

Views: 1374

Answers (1)

arogachev
arogachev

Reputation: 33548

I think it's overcomplication and you should not worry about it.

All Active Record attributes should stay editable. What these behaviors provide - it's just automation and some kind of abstraction.

But all you do with them is on your conscience as a programmer.

Sometimes it still can be useful to modify them manually, so lock it completely does not make any sense.

The only thing you should really care about is to exclude them from massive assignment from rules() section so user can't modify it. This should be done with all manually processed attributes, don't forget that.

Hope it helps.

Upvotes: 3

Related Questions