public function filters() { return ['accessControl']; }
public function accessRules() {
return [
['allow', 'actions'=>['index','view'], 'users'=>['*']], // 所有人
['allow', 'actions'=>['create','update'], 'users'=>['@']], // 登錄用戶
['allow', 'actions'=>['admin','delete'], 'users'=>['admin']],// 指定用戶
['deny', 'users'=>['*']], // 拒絕其餘
];
}
users 支持 *(所有人)、@(已登錄)、?(游客)、具體用戶名。亦可用 roles 配合 RBAC。
public function filters() { return ['rights']; }
Rights 提供圖形化後台管理角色、任務、操作權限,適合中大型項目。需先遷移數據庫表並配置 authManager 組件。
public function filters() {
return [
'updateOwn + update', // 僅 update 動作應用此過濾器
'rights', // 其他動作走 RBAC
];
}
public function filterUpdateOwn($filterChain) {
$post = $this->loadModel();
// 若用戶擁有 'PostUpdateOwn' 權限且是作者,移除 rights 過濾器放行
if (Yii::app()->user->checkAccess('PostUpdateOwn', ['userid'=>$post->author_id])) {
$filterChain->controller->filters()->removeAt(1); // 移除 rights
}
$filterChain->run();
}
適用場景:資源擁有者可編輯自己的內容,超級管理員走 RBAC 統一管理。
public function allowedActions() { return 'autocomplete,autocomplete2'; }
| 方案 | 適用場景 | 複雜度 |
|---|---|---|
| accessControl | 簡單項目、少量角色、靜態權限 | 低 |
| Rights | 需後台可視化管理權限、多角色多層級 | 中 |
| 混合模式 | 資源所有權判斷 + RBAC 共存 | 高 |