PHPackages                             mixartemev/yii2-db-rbac - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. mixartemev/yii2-db-rbac

ActiveYii2-extension[Authentication &amp; Authorization](/categories/authentication)

mixartemev/yii2-db-rbac
=======================

Dynamic control of access rights in YII2

1.0.12(9y ago)0861MITPHP

Since Jul 15Pushed 9y ago3 watchersCompare

[ Source](https://github.com/mixartemev/yii2-db-rbac)[ Packagist](https://packagist.org/packages/mixartemev/yii2-db-rbac)[ RSS](/packages/mixartemev-yii2-db-rbac/feed)WikiDiscussions master Synced yesterday

READMEChangelogDependencies (1)Versions (15)Used By (0)

Dynamic Access Control for Yii2
===============================

[](#dynamic-access-control-for-yii2)

##### НА РУССКОМ [ТУТ](https://github.com/mixartemev/yii2-db-rbac/blob/master/README.RU.md)

[](#на-русском-тут)

The easiest way to create access control in Yii2 without changes in the code.

This module allows creating roles and rules for Yii role base access (RBAC) via UI. It also allows assigning roles and rules for user via UI. Behaviour that checks access by the modules rules.

### Installation guide

[](#installation-guide)

```
$ php composer.phar require mixartemev/yii2-db-rbac "*"
```

To work correctly, you must configure the module `authManager` in the application config file (`common/config/main.php` for advanced app or `config/web.php` and `config/console` for basic app)

```
    'components' => [
       'authManager' => [
          'class' => 'yii\rbac\DbManager',
        ],
    ...
    ]
```

Run migration to create `DbManager` table (it means that a connection to the database is already configured for the application)

```
$ yii migrate --migrationPath=@yii/rbac/migrations/
```

Add the module
--------------

[](#add-the-module)

Include module to the config file (`backend/config/main.php` for advanced app or `config/web.php` for basic app)

```
  'modules' => [
        'permit' => [
            'class' => 'mixartemev\db_rbac\Yii2DbRbac',
        ],
    ],
```

If you want to setup layout, put it in the following way

```
  'modules' => [
        'permit' => [
            'class' => 'mixartemev\db_rbac\Yii2DbRbac',
            'layout' => '//admin'
        ],
    ],
```

If you use CNC, be sure that you have correct routing rules for modules

```
'//' => '//',
'///' => '//',
```

**Adding links**

**/permit/access/role - manage roles**

**/permit/access/permission - manage access**

### Assigning role to a user

[](#assigning-role-to-a-user)

The module also has an interface for assigning roles to users.

To work correctly, the module should be specified with `User` class in the module parameters.

```
'modules' => [
        'permit' => [
            'class' => 'app\modules\db_rbac\Yii2DbRbac',
            'params' => [
                'userClass' => 'app\models\User'
            ]
        ],
    ],
```

User class should implement `mixartemev\db_rbac\interfaces\UserRbacInterface`. In most cases, you have to add function `getUserName()` which should return user's name.

```
use mixartemev\db_rbac\interfaces\UserRbacInterface;

class User extends ActiveRecord implements IdentityInterface, UserRbacInterface
{
...
    public function getUserName()
    {
       return $this->username;
    }
}
```

**For managing role for user with id=1, visit `/permit/user/view/1`**

The easiest way is to add this as a button in `GridView` with users list.

```
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'username',
        'email:email',

        ['class' => 'yii\grid\ActionColumn',
         'template' => '{view}&nbsp;&nbsp;{update}&nbsp;&nbsp;{permit}&nbsp;&nbsp;{delete}',
         'buttons' =>
             [
                 'permit' => function ($url, $model) {
                     return Html::a('', Url::to(['/permit/user/view', 'id' => $model->id]), [
                         'title' => Yii::t('yii', 'Change user role')
                     ]); },
             ]
        ],
    ],
]);
```

You can also assign a role to the user in the code, for example when user has been created.

```
$userRole = Yii::$app->authManager->getRole('name_of_role');
Yii::$app->authManager->assign($userRole, $user->getId());
```

You also can check if a user has access in code thought `can()` method in User class

```
Yii::$app->user->can($permissionName);
```

$permissionName - could be a role name or a permission name.

Behaviour that checks access by the modules rules
-------------------------------------------------

[](#behaviour-that-checks-access-by-the-modules-rules)

By using this behaviour you don't need to write `Yii::$app->user->can($permissionName)` in each action. Behaviour will check it automatically. It is also useful for access control with the third party modules.

### Configure behaviour

[](#configure-behaviour)

You have to include behaviour to the app config file, if you want to check access automatically.

```
use mixartemev\db_rbac\behaviors\AccessBehavior;

 'as AccessBehavior' => [
        'class' => AccessBehavior::className(),
 ]
```

On `EVENT_BEFORE_ACTION` behaviour will check access for current user (`Yii::$app->user`) to the action. Action is allowed if:

- a user has access to the action (rule: module/controller/action)
- a user has acceess to any action in the controller (rule: module/controller)
- a user has access to any action in the module (rule: module)

### Redirection if access denied

[](#redirection-if-access-denied)

By default if a user doesn't have access, behaviour will throw `ForbiddenHttpException`. Application can handle this exception as needed.

You also can configure `login_url` where unauthorized user will be redirected, or `redirect_url` for redirecting a user when access is denied.

```
    'as AccessBehavior' => [
        'class' => AccessBehavior::className(),
        'redirect_url' => '/forbidden',
        'login_url' => Yii::$app->user->loginUrl
    ]
```

### Configure default access rules

[](#configure-default-access-rules)

After connecting behavior, access is available only to authorized users with certain rights. You can create default access rights in config file in the same way as you do in controller (`AccessControl`):

```
    'as AccessBehavior' => [
        'class' => AccessBehavior::className(),
        'rules' =>
            ['site' =>
                [
                    [
                        'actions' => ['login', 'index'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['about'],
                        'allow' => true,
                        'roles' => ['admin'],
                    ],
                ]
            ]
    ]
```

In this example any user has access to `site/login` and `site/index` and only user with role `admin` has access to `site/about`. The rules described in the configuration take precedence over dynamically configurable rules.

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 56.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~39 days

Recently: every ~98 days

Total

13

Last Release

3529d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/5181924?v=4)[Mike Artemiev](/maintainers/mixartemev)[@mixartemev](https://github.com/mixartemev)

---

Top Contributors

[![mixartemev](https://avatars.githubusercontent.com/u/5181924?v=4)](https://github.com/mixartemev "mixartemev (35 commits)")[![developeruz](https://avatars.githubusercontent.com/u/8788118?v=4)](https://github.com/developeruz "developeruz (25 commits)")[![astapb74](https://avatars.githubusercontent.com/u/5867042?v=4)](https://github.com/astapb74 "astapb74 (1 commits)")[![xloading](https://avatars.githubusercontent.com/u/1406364?v=4)](https://github.com/xloading "xloading (1 commits)")

---

Tags

rbacyii

### Embed Badge

![Health badge](/badges/mixartemev-yii2-db-rbac/health.svg)

```
[![Health](https://phpackages.com/badges/mixartemev-yii2-db-rbac/health.svg)](https://phpackages.com/packages/mixartemev-yii2-db-rbac)
```

###  Alternatives

[developeruz/yii2-db-rbac

Dynamic control of access rights in YII2

11098.5k5](/packages/developeruz-yii2-db-rbac)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
