PHPackages                             casbin/webman-permission - 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. casbin/webman-permission

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

casbin/webman-permission
========================

webman casbin permission plugin

v2.4.5(2mo ago)523.4k↓25%17[1 issues](https://github.com/php-casbin/webman-permission/issues)2MITPHPPHP &gt;=8.0CI passing

Since Mar 23Pushed 2mo ago6 watchersCompare

[ Source](https://github.com/php-casbin/webman-permission)[ Packagist](https://packagist.org/packages/casbin/webman-permission)[ RSS](/packages/casbin-webman-permission/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (28)Versions (33)Used By (2)

 [![workbunny](./workbunny-logo.png)](./workbunny-logo.png)

 **🐇 An Authorization Library for Webman Plugin 🐇**

 🐇 Webman Authorization Plugin Based on Casbin 🐇
=================================================

[](#---webman-authorization-plugin-based-on-casbin-)

 [ ![Build Status](https://github.com/php-casbin/webman-permission/actions/workflows/default.yml/badge.svg?branch=main) ](https://github.com/php-casbin/webman-permission/actions/workflows/default.yml) [ ![Latest Stable Version](https://camo.githubusercontent.com/51bfb469865ca5e1ffa964ed41dc7451311836ffdf6a58e958bc5de45ab3313c/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f7765626d616e2d7065726d697373696f6e2f762f737461626c65) ](https://packagist.org/packages/casbin/webman-permission) [ ![Total Downloads](https://camo.githubusercontent.com/e8d2386df24f780de8f5ec263f26fbaa54028360d6360fd8e259b4b1d235a9a4/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f7765626d616e2d7065726d697373696f6e2f646f776e6c6f616473) ](https://packagist.org/packages/casbin/webman-permission) [ ![License](https://camo.githubusercontent.com/47628fc75b96a5f43ab605c03ae434ad3582b9c5d06df7b4c92bba1728a8995f/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f7765626d616e2d7065726d697373696f6e2f6c6963656e7365) ](https://packagist.org/packages/casbin/webman-permission)

> An authorization library that supports access control models like ACL, RBAC, ABAC for Webman plugin.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Configuration](#configuration)
    - [Dependency Injection](#dependency-injection)
    - [Database Configuration](#database-configuration)
- [Usage](#usage)
- [Multiple Driver Configuration](#multiple-driver-configuration)
- [Tutorials](#tutorials)
- [Testing](#testing)
- [Contributing](#contributing)
- [Credits](#credits)
- [Troubleshooting](#troubleshooting)

---

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

[](#installation)

Install the package via Composer:

```
composer require -W casbin/webman-permission
```

---

Configuration
-------------

[](#configuration)

### Dependency Injection

[](#dependency-injection)

Modify the `config/container.php` configuration file as follows:

```
$builder = new \DI\ContainerBuilder();
$builder->addDefinitions(config('dependence', []));
$builder->useAutowiring(true);
return $builder->build();
```

### Database Configuration

[](#database-configuration)

By default, the policy storage uses **ThinkORM**.

#### 1. Model Configuration

[](#1-model-configuration)

The default uses ThinkORM. Modify the database configuration in `config/thinkorm.php`.

> **Note:** If using Laravel database, configure as follows:
>
> - Modify the database configuration in `config/database.php`
> - Change the `adapter` in `config/plugin/casbin/webman-permission/permission.php` to the Laravel adapter

#### 2. Create `casbin_rule` Table

[](#2-create-casbin_rule-table)

Execute the following SQL to create the policy rules table:

```
CREATE TABLE `casbin_rule` (
    `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    `ptype` VARCHAR(128) NOT NULL DEFAULT '',
    `v0` VARCHAR(128) NOT NULL DEFAULT '',
    `v1` VARCHAR(128) NOT NULL DEFAULT '',
    `v2` VARCHAR(128) NOT NULL DEFAULT '',
    `v3` VARCHAR(128) NOT NULL DEFAULT '',
    `v4` VARCHAR(128) NOT NULL DEFAULT '',
    `v5` VARCHAR(128) NOT NULL DEFAULT '',
    PRIMARY KEY (`id`) USING BTREE,
    KEY `idx_ptype` (`ptype`) USING BTREE,
    KEY `idx_v0` (`v0`) USING BTREE,
    KEY `idx_v1` (`v1`) USING BTREE,
    KEY `idx_v2` (`v2`) USING BTREE,
    KEY `idx_v3` (`v3`) USING BTREE,
    KEY `idx_v4` (`v4`) USING BTREE,
    KEY `idx_v5` (`v5`) USING BTREE
) ENGINE = INNODB CHARSET = utf8mb4 COMMENT = 'Casbin Policy Rules Table';
```

#### 3. Configure Redis

[](#3-configure-redis)

Configure your Redis settings in `config/redis.php`.

#### 4. Restart Webman

[](#4-restart-webman)

```
# Restart in foreground
php start.php restart

# Or restart in daemon mode
php start.php restart -d
```

---

Usage
-----

[](#usage)

After successful installation, you can use the library as follows:

### Basic Operations

[](#basic-operations)

```
use Casbin\WebmanPermission\Permission;

// Add permissions to a user
Permission::addPermissionForUser('eve', 'articles', 'read');

// Add a role for a user
Permission::addRoleForUser('eve', 'writer');

// Add permissions to a role
Permission::addPolicy('writer', 'articles', 'edit');
```

### Permission Check

[](#permission-check)

```
if (\Casbin\WebmanPermission\Permission::enforce('eve', 'articles', 'edit')) {
    echo 'Congratulations! Permission granted.';
} else {
    echo 'Sorry, you do not have access to this resource.';
}
```

---

Multiple Driver Configuration
-----------------------------

[](#multiple-driver-configuration)

You can use multiple driver configurations:

```
$permission = \Casbin\WebmanPermission\Permission::driver('restful_conf');

// Add permissions to a user
$permission->addPermissionForUser('eve', 'articles', 'read');

// Add a role for a user
$permission->addRoleForUser('eve', 'writer');

// Add permissions to a role
$permission->addPolicy('writer', 'articles', 'edit');

// Check permissions
if ($permission->enforce('eve', 'articles', 'edit')) {
    echo 'Congratulations! Permission granted.';
} else {
    echo 'Sorry, you do not have access to this resource.';
}
```

For more API details, refer to the [Casbin API Documentation](https://casbin.org/docs/en/management-api).

---

Tutorials
---------

[](#tutorials)

- [Casbin Permission Practice: Getting Started (Chinese)](https://www.bilibili.com/video/BV1A541187M4/?vd_source=a9321be9ed112f8d6fdc8ee87640be1b)
- [Casbin Permission Practice: RBAC Authorization Based on Roles (Chinese)](https://www.bilibili.com/video/BV1A541187M4/?vd_source=a9321be9ed112f8d6fdc8ee87640be1b)
- [Casbin Permission Practice: RESTful and Middleware Usage (Chinese)](https://www.bilibili.com/video/BV1uk4y117up/?vd_source=a9321be9ed112f8d6fdc8ee87640be1b)
- [Casbin Permission Practice: Using Custom Matching Functions (Chinese)](https://www.bilibili.com/video/BV1dq4y1Z78g/?vd_source=a9321be9ed112f8d6fdc8ee87640be1b)
- [Webman Practice Tutorial: Using Casbin Permission Control (Chinese)](https://www.bilibili.com/video/BV1X34y1Q7ZH/?vd_source=a9321be9ed112f8d6fdc8ee87640be1b)

---

Testing
-------

[](#testing)

This project includes a comprehensive unit test suite covering the following aspects:

### Test File Structure

[](#test-file-structure)

```
tests/
├── Adapter.php                    # Basic adapter tests
├── PermissionTest.php            # Permission class tests
├── AdapterTest.php               # Detailed adapter tests
├── EdgeCaseTest.php              # Edge case tests
├── IntegrationTest.php           # Integration tests
├── LaravelDatabase/
│   ├── LaravelDatabaseAdapterTest.php
│   └── TestCase.php
├── ThinkphpDatabase/
│   ├── DatabaseAdapterTest.php
│   └── TestCase.php
└── config/
    └── plugin/
        └── casbin/
            └── webman-permission/
                └── permission.php

```

### Test Coverage

[](#test-coverage)

1. **Basic Functionality**

    - Permission add, remove, check
    - Role assignment, removal
    - Policy management
2. **Adapter Tests**

    - Database operations
    - Filter functionality
    - Batch operations
    - Transaction handling
3. **Edge Cases**

    - Null value handling
    - Special characters
    - Large data volumes
    - Performance testing
4. **Integration Tests**

    - Complete RBAC workflow
    - Domain permission control
    - Multi-driver support
    - Complex business scenarios
5. **Error Handling**

    - Exception scenarios
    - Invalid input
    - Concurrent access

### Running Tests

[](#running-tests)

```
# Run all tests
php vendor/bin/phpunit tests/

# Run specific test file
php vendor/bin/phpunit tests/PermissionTest.php

# Run specific test method
php vendor/bin/phpunit --filter testAddPermissionForUser tests/PermissionTest.php

# Generate coverage report
php vendor/bin/phpunit --coverage-html coverage tests/
```

### Requirements

[](#requirements)

- PHP &gt;= 8.1
- PHPUnit &gt;= 9.0
- Database connection
- Redis connection

### Test Environment

[](#test-environment)

The test environment automatically creates the following tables:

- `casbin_rule` - Default policy table
- `other_casbin_rule` - Other driver policy table

### Best Practices

[](#best-practices)

1. **Writing New Tests**

    - Inherit from appropriate test base classes
    - Follow naming conventions
    - Add necessary assertions
2. **Test Data Management**

    - Use `setUp()` and `tearDown()` methods
    - Ensure test data isolation
    - Clean up test data
3. **Test Coverage**

    - Cover normal workflows
    - Test exception scenarios
    - Verify boundary conditions

---

Contributing
------------

[](#contributing)

### Adding New Features

[](#adding-new-features)

1. Write corresponding test cases for new features
2. Ensure test coverage meets requirements
3. Run the complete test suite
4. Check test status before submitting code

### Bug Fixes

[](#bug-fixes)

1. Write reproduction tests for bugs
2. Verify tests pass after fixing bugs
3. Ensure existing functionality is not affected

---

Credits
-------

[](#credits)

Built on top of [Casbin](https://github.com/php-casbin/php-casbin). For full documentation, visit the [official website](https://casbin.org/).

---

Advanced Configuration
----------------------

[](#advanced-configuration)

Removing PHP-DI Dependency (Not Recommended)1. Uninstall the DI dependency package:

```
composer remove php-di/php-di
```

2. Modify the `Casbin\WebmanPermission\Permission` file:

Replace:

```
if (is_null(static::$_manager)) {
    static::$_manager = new Enforcer($model, Container::get($config['adapter']), false);
}
```

With:

```
if (is_null(static::$_manager)) {
    if ($config['adapter'] == DatabaseAdapter::class) {
        $_model = new RuleModel();
    } elseif ($config['adapter'] == LaravelDatabaseAdapter::class) {
        $_model = new LaravelRuleModel();
    }
    static::$_manager = new Enforcer($model, new $config['adapter']($_model), false);
}
```

> **Warning:** This approach has high coupling and is not recommended. For more information, visit:

---

Troubleshooting
---------------

[](#troubleshooting)

### Think-ORM 4.0 Compatibility

[](#think-orm-40-compatibility)

**Error:** `Object not contained in WeakMap` or `array_search(): Argument #2 ($haystack) must be of type array, null given`

**Solution:** This package fully supports think-orm 4.0+. If you encounter WeakMap errors:

1. Ensure you're using the latest version:

```
composer require casbin/webman-permission:^2.4
```

2. For detailed information, see:
    - [Think-ORM 4.0 Fix Guide](./THINK_ORM_4_FIX.md)
    - [Think-ORM Compatibility Guide](./THINK_ORM_COMPATIBILITY.md)

**Supported Versions:**

- ✅ think-orm 2.0.53+
- ✅ think-orm 3.x
- ✅ think-orm 4.0.30+

### Laravel Driver Error

[](#laravel-driver-error)

**Error:** `Call to a member function connection() on null`

**Solution:** Check if your local database proxy is working correctly. Using Docker container host addresses like `dnmp-mysql` may cause this issue.

---

License
-------

[](#license)

[MIT License](LICENSE)

###  Health Score

55

—

FairBetter than 98% of packages

Maintenance87

Actively maintained with recent releases

Popularity35

Limited adoption so far

Community24

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 70.4% 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 ~47 days

Recently: every ~2 days

Total

32

Last Release

64d ago

Major Versions

v1.2.x-dev → v2.0.02024-11-01

PHP version history (2 changes)v1.0.0PHP &gt;=7.4

v2.0.0PHP &gt;=8.0

### Community

Maintainers

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

---

Top Contributors

[![Tinywan](https://avatars.githubusercontent.com/u/14959876?v=4)](https://github.com/Tinywan "Tinywan (76 commits)")[![houaiai](https://avatars.githubusercontent.com/u/25687708?v=4)](https://github.com/houaiai "houaiai (15 commits)")[![lyt8384](https://avatars.githubusercontent.com/u/3069157?v=4)](https://github.com/lyt8384 "lyt8384 (6 commits)")[![leeqvip](https://avatars.githubusercontent.com/u/35752209?v=4)](https://github.com/leeqvip "leeqvip (5 commits)")[![lly0414](https://avatars.githubusercontent.com/u/30135049?v=4)](https://github.com/lly0414 "lly0414 (3 commits)")[![akroa](https://avatars.githubusercontent.com/u/221409693?v=4)](https://github.com/akroa "akroa (2 commits)")[![sunsgneayo](https://avatars.githubusercontent.com/u/51745500?v=4)](https://github.com/sunsgneayo "sunsgneayo (1 commits)")

---

Tags

aclauthauthorizationcasbincasbin-adaptercasbin-watcherpermissionphprbacthinkphptinywanwebmanworkermanauthorizationaclpermissionrbacworkermanaccess-controlabaccasbinauthzwebman

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/casbin-webman-permission/health.svg)

```
[![Health](https://phpackages.com/badges/casbin-webman-permission/health.svg)](https://phpackages.com/packages/casbin-webman-permission)
```

###  Alternatives

[casbin/laravel-authz

An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.

324339.9k4](/packages/casbin-laravel-authz)[casbin/casbin

a powerful and efficient open-source access control library for php projects.

1.3k1.4M54](/packages/casbin-casbin)[casbin/think-authz

An authorization library that supports access control models like ACL, RBAC, ABAC for ThinkPHP.

27918.5k6](/packages/casbin-think-authz)[casbin/codeigniter-permission

Associate users with roles and permissions, use Casbin in CodeIgniter4 Web Framework.

443.0k](/packages/casbin-codeigniter-permission)[hosseinhezami/laravel-permission-manager

Advanced permission manager for Laravel.

403.3k](/packages/hosseinhezami-laravel-permission-manager)

PHPackages © 2026

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