Yii型号默认值。干

时间:2013-02-05 03:44:04

标签: model yii dry

我正在编写多用户应用程序。在每个模型中我都有一个字段user_id,每个用户登录,我可以得到他的身份:Yii::app()->user->id

我不想在每个动作查找/更新/插入条件中重复它,所以如何在模型user_id中设置它?

2 个答案:

答案 0 :(得分:1)

使用CActiveRecordBehavior。这样你就可以为所有模型挂钩beforeFind / afterFind和beforeSave / afterSave事件。这真的很不错

答案 1 :(得分:0)

您必须创建父类并继承它

abstract class UserAccess extends CActiveRecord {

    public function getUserAccessCondition($condition, array $params)
    {
        if ($condition instanceof CDbCriteria) {
            $condition->compare('user_id', Yii::app()->user->id);
        } else {
            if(!is_array($condition)) {
                $condition['condition'] = $condition;
                $condition['params'] = $params;
            }
            if (trim($condition['condition']) == '') $condition['condition'] = 'user_id=:user_id';
            else $condition['condition'] .= ' and user_id=:user_id';
            $params[':user_id'] = Yii::app()->user->id;
        }
        return $condition;
    }

    public function find($condition='',$params=array())
    {
        $condition = $this->getUserAccessCondition($condition, $params);
        parent::find($condition, $params);
    }
    // and so on in findAll,  findAttributes...
    // for findByPk you need make some things maybe after find 
    // chek user_id and if is not equal throw access denied exception 
    public function afterFind()
    {
        if ($this->user_id != Yii::app()->user->id) {
            throw new CHttpException(403, 'Access Denied');
        }
    }
}


class UserItem extends UserAccess
{
   //.. rules tableName etc

}
// simple call
$userItem = UserItem::model()->find('name=:name', array(':name' => 'Some search name'));