【问题标题】:RBAC in Yii2 with PhpManagerYii2 中的 RBAC 和 PhpManager
【发布时间】:2015-03-22 07:34:43
【问题描述】:

如何在没有任何数据库的情况下在Yii 2.0 中实现RBAC。 我将只有 2 个角色,即 admin and author 。 我的 RbacController 是

<?php
namespace app\commands;

use Yii;
use yii\console\Controller;

class RbacController extends Controller
{
    public function actionInit()
    {
        $auth =  \Yii::$app->authManager;

        // add "createPost" permission
        $createPost = $auth->createPermission('createPost');
        $createPost->description = 'Create a post';
        $auth->add($createPost);

        // add "updatePost" permission
        $updatePost = $auth->createPermission('updatePost');
        $updatePost->description = 'Update post';
        $auth->add($updatePost);

        // add "author" role and give this role the "createPost" permission
        $author = $auth->createRole('author');
        $auth->add($author);
        $auth->addChild($author, $createPost);

        // add "admin" role and give this role the "updatePost" permission
        // as well as the permissions of the "author" role
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        $auth->addChild($admin, $updatePost);
        $auth->addChild($admin, $author);

        // Assign roles to users. 1 and 2 are IDs returned by IdentityInterface::getId()
        // usually implemented in your User model.
        $auth->assign($author, 2);
        $auth->assign($admin, 1);
    }
}

我收到一个错误

  `PHP Fatal error: Call to a member function createPermission() 
on a non-object in var/www/commands/RbacController.php on line 14
    PHP Fatal Error 'yii\base\ErrorException' with message 'Call to a member
 function createPermission() on a non-object' in /var/www/commands/RbacController.php:14 

在执行 yii rbac/init 时。我正在使用带有 PhpManager 的基本模板。我在 web.php 中添加了'authManager' =&gt; [ 'class' =&gt; 'yii\rbac\PhpManager', ],。我使用的是基本模板。

【问题讨论】:

    标签: yii2 rbac


    【解决方案1】:

    我知道这有点旧,但我想发布解决方案.. 至少对我有用。

    我添加了 'authManager' => [ 'class' => 'yii\rbac\PhpManager', ], 在 web.php 中

    有错误,因为你是通过控制台运行命令,你需要在console.php的组件部分添加相同的行(与web.php在同一目录中)。

    我希望这可以帮助其他有类似问题的人:D

    【讨论】:

    • 或者将其添加到通用配置main.php中,以便所有应用程序都可以使用。
    【解决方案2】:

    【讨论】:

    • 发布你的 RbacController
    【解决方案3】:

    在你的控制器中试试这个

    $auth = new \yii\rbac\PhpManager();
     // add "createPost" permission
    $createPost = $auth->createPermission('createPost');
    $createPost->description = 'Create a post';
    $auth->add($createPost);
    

    http://blog.dedikisme.com/blog/2014/05/09/rpbac-yii2-framework

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2016-08-26
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      相关资源
      最近更新 更多