I want create and add a Rule in {{%auth_rule}} table of my db in yii2 app.
I can’t find any document or guide for do this operation in yii2. but i found addRule($rule) method in yii\rbac\DbManager and i think, i should use this method for do this but i don’t know how?
Whether i should create a class for any Rules in @app\rbac or this method just used for PhpManager?
namespace console\controllers;
use Yii;
use yii\console\Controller;
use console\models\OwnRule;
class RbacController extends Controller {
public function actionInit() {
$auth = Yii::$app->authManager;
$auth->removeAll();
//add the rule
$rule = new OwnRule();
$auth->add($rule);
// add the "updateOwn" permission and associate the rule with it.
$updateOwn = $auth->createPermission('updateOwn');
$updateOwn->description = 'update own';
$updateOwn->ruleName = $rule->name;
$auth->add($updateOwn);
// add "admin" role and give this role
$admin = $auth->createRole('admin');
$auth->add($admin);
// Assign roles to admin. 1 is ID returned by IdentityInterface::getId()
// usually implemented in your User model.
$auth->assign($admin, 1);
}
}
An RBAC rule must be written as a class that extends yii\rbac\Rule and stored in an ordinary php file. Then you can add it to the authManager, which can be either DbManager or PhpManager. It doesn’t matter.
$auth = Yii::$app->authManager;
//add the rule
$rule = new OwnRule();
$auth->add($rule);
// add the "updateOwn" permission and associate the rule with it.
$updateOwn = $auth->createPermission('updateOwn');
$updateOwn->description = 'update own';
$updateOwn->ruleName = $rule->name;
$auth->add($updateOwn);
// add "admin" role and give this role
$admin = $auth->createRole('admin');
$auth->add($admin);
The code above comes from the post of Armand. This is what you have to do. And note that you have to write "OwnRule.php" somewhere in your source directory before you do this.