PHPackages                             yiisoft/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. [Framework](/categories/framework)
4. /
5. yiisoft/rbac

ActiveLibrary[Framework](/categories/framework)

yiisoft/rbac
============

Yii Role-Based Access Control

2.1.2(6mo ago)76170.4k—4%26[11 issues](https://github.com/yiisoft/rbac/issues)[2 PRs](https://github.com/yiisoft/rbac/pulls)9BSD-3-ClausePHPPHP 8.1 - 8.5CI passing

Since Apr 8Pushed 1w ago20 watchersCompare

[ Source](https://github.com/yiisoft/rbac)[ Packagist](https://packagist.org/packages/yiisoft/rbac)[ Docs](https://www.yiiframework.com/)[ GitHub Sponsors](https://github.com/sponsors/yiisoft)[ OpenCollective](https://opencollective.com/yiisoft)[ RSS](/packages/yiisoft-rbac/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (6)Dependencies (11)Versions (15)Used By (9)

 [ ![Yii](https://camo.githubusercontent.com/8317c17418b39410a660f5149071d26c5023c0d5fb2b7ebb771324812f666d73/68747470733a2f2f796969736f66742e6769746875622e696f2f646f63732f696d616765732f7969695f6c6f676f2e737667) ](https://github.com/yiisoft)

Yii Role-Based Access Control
=============================

[](#yii-role-based-access-control)

[![Latest Stable Version](https://camo.githubusercontent.com/f274a2da75b114c75a5a702168ea32ead84332aa0ea09f7907615dfc2b9268ab/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f726261632f76)](https://packagist.org/packages/yiisoft/rbac)[![Total Downloads](https://camo.githubusercontent.com/5befa9dc067386b8417943596796dcac6aa5a20ffd8d7f315e3e2db0652a8726/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f726261632f646f776e6c6f616473)](https://packagist.org/packages/yiisoft/rbac)[![Build status](https://github.com/yiisoft/rbac/actions/workflows/build.yml/badge.svg)](https://github.com/yiisoft/rbac/actions/workflows/build.yml)[![codecov](https://camo.githubusercontent.com/50e71ceb6b2e5aa983415a42945a212d44d744bde381ed9471613c43d480380c/68747470733a2f2f636f6465636f762e696f2f67682f796969736f66742f726261632f67726170682f62616467652e7376673f746f6b656e3d39355356575945584f31)](https://codecov.io/gh/yiisoft/rbac)[![Mutation testing badge](https://camo.githubusercontent.com/080d7729eacda876dde97f3bd125215b0afebb08ec3ea6bf7e068ce491e28b21/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d253246796969736f6674253246726261632532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/rbac/master)[![static analysis](https://github.com/yiisoft/rbac/workflows/static%20analysis/badge.svg)](https://github.com/yiisoft/rbac/actions?query=workflow%3A%22static+analysis%22)[![type-coverage](https://camo.githubusercontent.com/1e88eed856191464fe3bf6100a6ba76a0187e6220608a7ae422c291189e55d50/68747470733a2f2f73686570686572642e6465762f6769746875622f796969736f66742f726261632f636f7665726167652e737667)](https://shepherd.dev/github/yiisoft/rbac)

This package provides [RBAC](https://en.wikipedia.org/wiki/Role-based_access_control) (Role-Based Access Control) library. It is used in [Yii Framework](https://yiiframework.com) but is usable separately as well.

Features
--------

[](#features)

- Flexible RBAC hierarchy with roles, permissions, and rules.
- Role inheritance.
- Data could be passed to rules when checking access.
- Multiple storage adapters.
- Separate storages could be used for user-role assignments and role hierarchy.
- API to manage RBAC hierarchy.

Requirements
------------

[](#requirements)

- PHP 8.1 - 8.5.

Installation
------------

[](#installation)

The package could be installed with [Composer](https://getcomposer.org):

```
composer require yiisoft/rbac
```

One of the following storages could be installed as well:

- [PHP storage](https://github.com/yiisoft/rbac-php) - PHP file storage;
- [DB storage](https://github.com/yiisoft/rbac-db) - database storage based on [Yii DB](https://github.com/yiisoft/db);
- [Cycle DB storage](https://github.com/yiisoft/rbac-cycle-db) - database storage based on [Cycle DBAL](https://github.com/cycle/database).

Also, there is a rule factory implementation - [Rules Container](https://github.com/yiisoft/rbac-rules-container) (based on [Yii Factory](https://github.com/yiisoft/factory)).

All these can be replaced with custom implementations.

General usage
-------------

[](#general-usage)

### Setting up manager

[](#setting-up-manager)

First step when using RBAC is to configure an instance of `Manager`:

```
use Yiisoft\Rbac\AssignmentsStorageInterface;
use Yiisoft\Rbac\ItemsStorageInterface;
use Yiisoft\Rbac\RuleFactoryInterface;

/**
* @var ItemsStorageInterface $itemsStorage
* @var AssignmentsStorageInterface $assignmentsStorage
* @var RuleFactoryInterface $ruleFactory
*/
$manager = new Manager($itemsStorage, $assignmentsStorage, $ruleFactory);
```

It requires the following dependencies:

- Items storage (hierarchy itself).
- Assignments storage where user IDs are mapped to roles.
- Rule factory. Creates a rule instance by a given name.

While storages are required, rule factory is optional and, when omitted, `SimpleRuleFactory` will be used. For more advanced usage, such as resolving rules by aliases and passing arguments in rules constructor, install [Rules Container](https://github.com/yiisoft/rbac-rules-container) additionally or write your own implementation.

A few tips for choosing storage backend:

- Roles and permissions could usually be considered "semi-static," as they only change when you update your application code, so it may make sense to use PHP storage for it.
- Assignments, on the other hand, could be considered "dynamic." They change more often: when creating a new user, or when updating a user role from within your application. So it may make sense to use database storage for assignments.

### Managing RBAC hierarchy

[](#managing-rbac-hierarchy)

Before being able to check for permissions, an RBAC hierarchy must be defined. Usually it is done via either console commands or migrations. Hierarchy consists of permissions, roles, and rules:

- Permissions are granules of access such as "create a post" or "read a post."
- A role is what is assigned to the user. The Role is granted one or more permissions. Typical roles are "manager" or "admin."
- Rule is a PHP class that has given some data answers a single question "given the data has the user the permission asked for."

To create a permission, use the following code:

```
use Yiisoft\Rbac\ManagerInterface;
use Yiisoft\Rbac\Permission;

/** @var ManagerInterface $manager */
$manager->addPermission(new Permission('createPost'));
$manager->addPermission(new Permission('readPost'));
$manager->addPermission(new Permission('deletePost'));
```

To add some roles:

```
use Yiisoft\Rbac\ManagerInterface;
use Yiisoft\Rbac\Role;

/** @var ManagerInterface $manager */
$manager->addRole(new Role('author'));
$manager->addRole(new Role('reader'));
```

Next, we need to attach permissions to roles:

```
use Yiisoft\Rbac\ManagerInterface;

/** @var ManagerInterface $manager */
$manager->addChild('reader', 'readPost');
$manager->addChild('author', 'createPost');
$manager->addChild('author', 'deletePost');
$manager->addChild('author', 'reader');
```

Hierarchy for the example above:

 ```
flowchart LR
  createPost:::permission ---> author:::role
  readPost:::permission --> reader:::role --> author:::role
  deletePost:::permission ---> author:::role
  classDef permission fill:#fc0,stroke:#000,color:#000
  classDef role fill:#9c0,stroke:#000,color:#000
```

      Loading Sometimes, basic permissions are not enough. In this case, rules are helpful. Rules are PHP classes that could be added to permissions and roles:

```
use Yiisoft\Rbac\Item;
use Yiisoft\Rbac\RuleContext;
use Yiisoft\Rbac\RuleInterface;

class ActionRule implements RuleInterface
{
    public function execute(?string $userId, Item $item, RuleContext $context): bool;
    {
        return $context->getParameterValue('action') === 'home';
    }
}
```

With rule added, the role or permission is considered only when rule's `execute()` method returns `true`.

The parameters are:

- `$userId` is user id to check permission against;
- `$item` is RBAC hierarchy item that rule is attached to;
- `$context` is a rule context providing access to parameters.

To use rules with `Manager`, specify their names with added permissions or roles:

```
use Yiisoft\Rbac\ManagerInterface;
use Yiisoft\Rbac\Permission;

/** @var ManagerInterface $manager */
$manager->addPermission(
    (new Permission('viewList'))->withRuleName(ActionRule::class),
);

// or

$manager->addRole(
    (new Role('NewYearMaintainer'))->withRuleName(NewYearOnlyRule::class)
);
```

The rule names `action_rule` and `new_year_only_rule` are resolved to `ActionRule` and `NewYearOnlyRule` class instances accordingly via rule factory.

If you need to aggregate multiple rules at once, use composite rule:

```
use Yiisoft\Rbac\CompositeRule;

// Fresh and owned
$compositeRule = new CompositeRule(CompositeRule::AND, [FreshRule::class, OwnedRule::class]);

// Fresh or owned
$compositeRule = new CompositeRule(CompositeRule::OR, [FreshRule::class, OwnedRule::class]);
```

### Assigning roles to users

[](#assigning-roles-to-users)

To assign a certain role to a user with a given ID, use the following code:

```
use Yiisoft\Rbac\ManagerInterface;

/** @var ManagerInterface $manager */
$userId = 100;
$manager->assign('author', $userId);
```

It could be done in an admin panel, via console command, or it could be built into the application business logic itself.

### Check for permission

[](#check-for-permission)

To check for permission, obtain an instance of `Yiisoft\Access\AccessCheckerInterface` and use it:

```
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Access\AccessCheckerInterface;

public function actionCreate(AccessCheckerInterface $accessChecker): ResponseInterface
{
    $userId = getUserId();

    if ($accessChecker->userHasPermission($userId, 'createPost')) {
        // author has permission to create post
    }
}
```

Sometimes you need to add guest-only permission, which is not assigned to any user ID. In this case, you can specify a role which is assigned to guest user:

```
use Yiisoft\Access\AccessCheckerInterface;
use Yiisoft\Rbac\Permission;
use Yiisoft\Rbac\Role;

/**
 * @var ManagerInterface $manager
 * @var AccessCheckerInterface $accessChecker
 */
$manager->setGuestRoleName('guest');
$manager->addPermission(new Permission('signup'));
$manager->addRole(new Role('guest'));
$manager->addChild('guest', 'signup');

$guestId = null;
if ($accessChecker->userHasPermission($guestId, 'signup')) {
    // Guest has "signup" permission.
}
```

If there is a rule involved, you may pass extra parameters:

```
use Yiisoft\Rbac\ManagerInterface;

/** @var ManagerInterface $manager */
$anotherUserId = 103;
if (!$manager->userHasPermission($anotherUserId, 'viewList', ['action' => 'home'])) {
    echo 'reader hasn\'t "index" permission';
}
```

Documentation
-------------

[](#documentation)

- [Internals](docs/internals.md)

If you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for that. You may also check out other [Yii Community Resources](https://www.yiiframework.com/community).

License
-------

[](#license)

The Yii Role-Based Access Control is free software. It is released under the terms of the BSD License. Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).

Support the project
-------------------

[](#support-the-project)

[![Open Collective](https://camo.githubusercontent.com/a2b15f8e2268d4e3842e00d41ff7a57cce2ad8bd8d8769c5dc4fa05a546a4f62/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4f70656e253230436f6c6c6563746976652d73706f6e736f722d3765616466313f6c6f676f3d6f70656e253230636f6c6c656374697665266c6f676f436f6c6f723d376561646631266c6162656c436f6c6f723d353535353535)](https://opencollective.com/yiisoft)

Follow updates
--------------

[](#follow-updates)

[![Official website](https://camo.githubusercontent.com/d6b0929173e28cc627430d2519ca1853466a70f37395877eaf4820cb3e1e1909/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f506f77657265645f62792d5969695f4672616d65776f726b2d677265656e2e7376673f7374796c653d666c6174)](https://www.yiiframework.com/)[![Twitter](https://camo.githubusercontent.com/d077c362ac639792171af8bc002ee827816733dfc0925f70b557e6d151022226/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f747769747465722d666f6c6c6f772d3144413146323f6c6f676f3d74776974746572266c6f676f436f6c6f723d314441314632266c6162656c436f6c6f723d3535353535353f7374796c653d666c6174)](https://twitter.com/yiiframework)[![Telegram](https://camo.githubusercontent.com/4e38dd12535575c39c65bea7119b95e663abb2d1f4e3d669a27bbda07ef603f0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74656c656772616d2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d74656c656772616d)](https://t.me/yii3en)[![Facebook](https://camo.githubusercontent.com/48204e301b34b29b0815854544f04c337fc0692096cab35e9a1f8c53a42c2307/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f66616365626f6f6b2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d66616365626f6f6b266c6f676f436f6c6f723d666666666666)](https://www.facebook.com/groups/yiitalk)[![Slack](https://camo.githubusercontent.com/1a3645ba1c97e6684d0349bc478201e1621ba0d3efad516d81035364d442bad7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f736c61636b2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d736c61636b)](https://yiiframework.com/go/slack)

###  Health Score

63

—

FairBetter than 99% of packages

Maintenance82

Actively maintained with recent releases

Popularity49

Moderate usage in the ecosystem

Community39

Small or concentrated contributor base

Maturity74

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~225 days

Recently: every ~243 days

Total

7

Last Release

196d ago

Major Versions

1.0.2 → 2.0.02024-03-07

PHP version history (4 changes)1.0.0PHP ^7.4|^8.0

2.0.0PHP ^8.1

2.1.0PHP 8.1 - 8.4

2.1.1PHP 8.1 - 8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/261a6249c6f605f3956a2fae40fbb813f6b2e1e6f2bf806180c851a965426e54?d=identicon)[cebe](/maintainers/cebe)

![](https://www.gravatar.com/avatar/fc29e4e7068a00fe9b9db37b8aadda1db6020adcacef810461e47b99c2b150e6?d=identicon)[samdark](/maintainers/samdark)

![](https://www.gravatar.com/avatar/ccb75e3312d6bd454ea445ea308139fd185a4ca906ca5df21cc66e6a35de25a3?d=identicon)[SilverFire](/maintainers/SilverFire)

![](https://www.gravatar.com/avatar/99106256c24a8cb23871b99fa90e48f37f1aa71608c185759b7d2a88683a5918?d=identicon)[hiqsol](/maintainers/hiqsol)

![](https://www.gravatar.com/avatar/53e5ee1dedd50f71e4aeeac2929f786cdfb400359d4776e6cd806388d0d5df2c?d=identicon)[vjik](/maintainers/vjik)

---

Top Contributors

[![arogachev](https://avatars.githubusercontent.com/u/8326201?v=4)](https://github.com/arogachev "arogachev (72 commits)")[![vjik](https://avatars.githubusercontent.com/u/525501?v=4)](https://github.com/vjik "vjik (37 commits)")[![samdark](https://avatars.githubusercontent.com/u/47294?v=4)](https://github.com/samdark "samdark (30 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (9 commits)")[![Fantom409](https://avatars.githubusercontent.com/u/14968877?v=4)](https://github.com/Fantom409 "Fantom409 (8 commits)")[![devanych](https://avatars.githubusercontent.com/u/20116244?v=4)](https://github.com/devanych "devanych (8 commits)")[![xepozz](https://avatars.githubusercontent.com/u/6815714?v=4)](https://github.com/xepozz "xepozz (4 commits)")[![terabytesoftw](https://avatars.githubusercontent.com/u/42547589?v=4)](https://github.com/terabytesoftw "terabytesoftw (3 commits)")[![roxblnfk](https://avatars.githubusercontent.com/u/4152481?v=4)](https://github.com/roxblnfk "roxblnfk (3 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (2 commits)")[![luizcmarin](https://avatars.githubusercontent.com/u/67489841?v=4)](https://github.com/luizcmarin "luizcmarin (2 commits)")[![rustamwin](https://avatars.githubusercontent.com/u/16498265?v=4)](https://github.com/rustamwin "rustamwin (2 commits)")[![darkdef](https://avatars.githubusercontent.com/u/8342004?v=4)](https://github.com/darkdef "darkdef (2 commits)")[![razonyang](https://avatars.githubusercontent.com/u/17720932?v=4)](https://github.com/razonyang "razonyang (1 commits)")[![DplusG](https://avatars.githubusercontent.com/u/11989901?v=4)](https://github.com/DplusG "DplusG (1 commits)")[![mspirkov](https://avatars.githubusercontent.com/u/63721828?v=4)](https://github.com/mspirkov "mspirkov (1 commits)")[![Arhell](https://avatars.githubusercontent.com/u/26163841?v=4)](https://github.com/Arhell "Arhell (1 commits)")[![sankaest](https://avatars.githubusercontent.com/u/21160342?v=4)](https://github.com/sankaest "sankaest (1 commits)")[![viktorprogger](https://avatars.githubusercontent.com/u/7670669?v=4)](https://github.com/viktorprogger "viktorprogger (1 commits)")

---

Tags

access-controlhacktoberfestrbacyii3rbacyii

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/yiisoft-rbac/health.svg)

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

###  Alternatives

[yiisoft/yii

Yii Web Programming Framework

4.8k5.9M268](/packages/yiisoft-yii)[yiisoft/yii2-queue

Yii2 Queue Extension which supports queues based on DB, Redis, RabbitMQ, Beanstalk, SQS, and Gearman

1.1k11.1M166](/packages/yiisoft-yii2-queue)[yiisoft/yii2-coding-standards

Yii PHP Framework Version 2 - Coding standard tools

1821.2M178](/packages/yiisoft-yii2-coding-standards)[yiisoft/access

An interface for checking access

31315.0k3](/packages/yiisoft-access)[yiisoft/yii-console

Symfony console wrapper with additional features

71443.8k42](/packages/yiisoft-yii-console)[yiisoft/form

The package helps with implementing data entry forms.

47108.4k1](/packages/yiisoft-form)

PHPackages © 2026

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