Yii框架权限控制概述
本内容详细解析了Yii框架下实现权限控制的几种典型方案,旨在为开发者提供实用的参考与借鉴。
以下梳理了三种常见的权限控制实现路径:
第一种方案是基于accessControl过滤器:
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow authenticated users to access all actions
'users'=>array('@'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
第二种方案是借助第三方插件(例如Rights):
public function filters()
{
return array(
'rights',
);
}
第三种方案采用混合模式:
/**
* @return array action filters
*/
public function filters()
{
return array(
'updateOwn + update', // Apply this filter only for the update action.
'rights',
);
}
/**
* Filter method for checking whether the currently logged in user
* is the author of the post being accessed.
*/
public function filterUpdateOwn($filterChain)
{
$post=$this->loadModel();
// Remove the 'rights' filter if the user is updating an own post
// and has the permission to do so.
if(Yii::app()->user->checkAccess('PostUpdateOwn', array('userid'=>$post->author_id)))
$filterChain->removeAt(1);
$filterChain->run();
}
在已具备基础权限的前提下,若需额外开放某些特定动作的访问权限,可利用allowedActions属性进行配置:
public function allowedActions()
{
return 'autocomplate,autocomplate2';
}
上述内容期望能为使用Yii框架进行PHP程序开发的读者带来实质性的帮助。