yii2 rbac接口开发实例
时间: 2024-01-15 15:04:49 浏览: 28
以下是Yii2 RBAC接口开发的实例:
1.首先,需要在配置文件中配置authManager组件:
```php
'components' => [
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
],
```
2.创建角色和权限:
```php
use yii\rbac\DbManager;
$auth = new DbManager;
$auth->init();
// 创建角色
$admin = $auth->createRole('admin');
$auth->add($admin);
// 创建权限
$createPost = $auth->createPermission('createPost');
$createPost->description = 'Create a post';
$auth->add($createPost);
```
3.将角色和权限关联起来:
```php
$auth->addChild($admin, $createPost);
```
4.在控制器中使用RBAC:
```php
use yii\web\Controller;
use yii\filters\AccessControl;
class PostController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['create'],
'allow' => true,
'roles' => ['createPost'],
],
],
],
];
}
public function actionCreate()
{
// 创建文章
}
}
```