一直想在小项目里采用RBAC ,可是内置的实在太强大了,对于小项目而言,是杀鸡用牛刀。看了cookbook里的Add information to Yii::app()->user by extending CWebUser 这篇文章, 深受启发:
1、为数据库的表User 增加一字段 “role” ; 填入你设的角色 例如“admin”“reader”“editor” ….
2、以下代码要保存在protected/components/WebUser.php
<?php
class WebUser extends CWebUser {
// Store model to not repeat query.
private $_model;
private $_access=array();
public function checkAccess($operation,$params=array(),$allowCaching=true)
{
if(isset($this->_access[$operation]))
return $this->_access[$operation];
else{
$user = $this->loadUser(Yii::app()->user->id);
return $this->_access[$operation]=$user->role===$operation?true:false;
}
}
protected function loadUser($id=null)
{
if($this->_model===null)
{
if($id!==null)
$this->_model=User::model()->findByPk($id);
}
return $this->_model;
}
}
3、
修改 protected/config/config.php
'components'=>array(
'user'=>array(
'class' => 'WebUser',
),
),
4、配置你的 accessRules(): 例如
public function accessRules()
{
return array(
array('allow', // allow readers only access to the view file
'actions'=>array('view'),
'roles'=>array('reader'),
),
array('allow', // allow editors only access to the update file
'actions'=>array('update'),
'roles'=>array('editor'),
),
);
}
也可在view里 用
<?php if(Yii::app()->user->checkAccess('editor')): ?>
<h3>Leave a Comment</h3>
.........//your /commnet/_form here
<?php endif; ?>