RBAC in Yii2 with PhpManager

How can I implement RBACin Yii 2.0without any database. I will have only two roles, i.e. admin and author. my 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);
    }
}

I get an error

  `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 

at execution yii rbac/init. I am using a basic template with PhpManager. I added 'authManager' => [ 'class' => 'yii\rbac\PhpManager', ],to web.php. I am using a basic template.

+4
source share
3 answers

The official documentation actually uses the php file https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md

+3
source

i Know that this is a bit outdated, but I want to post a solution .. at least that worked for me.

'authManager' = > ['class' = > 'yii\rbac\PhpManager',], web.php

, , console.php( , web.php).

, , : D

+8

try this in your controller

$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

0
source

All Articles