PHPackages                             casbin/dbal-adapter - 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. [Database &amp; ORM](/categories/database)
4. /
5. casbin/dbal-adapter

ActiveLibrary[Database &amp; ORM](/categories/database)

casbin/dbal-adapter
===================

Database Abstraction Layer adapter for php-casbin.

v3.1.0(1y ago)15105.2k↓30.2%71Apache-2.0PHPPHP &gt;=8.0CI failing

Since Sep 7Pushed 1y ago3 watchersCompare

[ Source](https://github.com/php-casbin/dbal-adapter)[ Packagist](https://packagist.org/packages/casbin/dbal-adapter)[ RSS](/packages/casbin-dbal-adapter/feed)WikiDiscussions master Synced yesterday

READMEChangelog (10)Dependencies (5)Versions (16)Used By (1)

Doctrine DBAL Adapter for Casbin
================================

[](#doctrine-dbal-adapter-for-casbin)

[![PHPUnit](https://github.com/php-casbin/dbal-adapter/actions/workflows/phpunit.yml/badge.svg)](https://github.com/php-casbin/dbal-adapter/actions/workflows/phpunit.yml)[![Coverage Status](https://camo.githubusercontent.com/f18a7e88f6d923d3897a46fac9382b21e87c38ccefdf971fcb6da5206809e488/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f7068702d63617362696e2f6462616c2d616461707465722f62616467652e737667)](https://coveralls.io/github/php-casbin/dbal-adapter)[![Latest Stable Version](https://camo.githubusercontent.com/4b98b601e59a9526adbbd04d6c14bd3be2ca9eca4d85f543859f63c00d4a34fb/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f6462616c2d616461707465722f762f737461626c65)](https://packagist.org/packages/casbin/dbal-adapter)[![Total Downloads](https://camo.githubusercontent.com/c3c5268afd3a19d66e11d61f023ea63c85055257a73fc727ec4382d56e9ef154/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f6462616c2d616461707465722f646f776e6c6f616473)](https://packagist.org/packages/casbin/dbal-adapter)[![License](https://camo.githubusercontent.com/2603bd1f6a9557111671d8021ac43917e33892a8d93f570183909383dbe18b61/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f6462616c2d616461707465722f6c6963656e7365)](https://packagist.org/packages/casbin/dbal-adapter)

Doctrine [DBAL](https://github.com/doctrine/dbal) Adapter for [PHP-Casbin](https://github.com/php-casbin/php-casbin), [Casbin](https://casbin.org/) is a powerful and efficient open-source access control library.

The following database vendors are currently supported:

- MySQL
- Oracle
- Microsoft SQL Server
- PostgreSQL
- SAP Sybase SQL Anywhere
- SQLite
- Drizzle

### Installation

[](#installation)

Via [Composer](https://getcomposer.org/).

```
composer require casbin/dbal-adapter

```

### Basic Usage (Without Redis Caching)

[](#basic-usage-without-redis-caching)

This section describes how to use the adapter with a direct database connection, without leveraging Redis for caching.

You can initialize the adapter by passing either a Doctrine DBAL connection parameter array or an existing `Doctrine\DBAL\Connection` instance to the `Adapter::newAdapter()` method or the `Adapter` constructor.

**Example:**

```
require_once './vendor/autoload.php';

use Casbin\Enforcer;
use CasbinAdapter\DBAL\Adapter as DatabaseAdapter;
use Doctrine\DBAL\DriverManager; // Required if creating a new connection object

// Option 1: Using DBAL connection parameters array
$dbConnectionParams = [
    // Supported drivers: pdo_mysql, pdo_sqlite, pdo_pgsql, pdo_oci, pdo_sqlsrv,
    // mysqli, sqlanywhere, sqlsrv, ibm_db2, drizzle_pdo_mysql
    'driver' => 'pdo_mysql',
    'host' => '127.0.0.1',
    'dbname' => 'casbin_db', // Your database name
    'user' => 'root',
    'password' => '',
    'port' => '3306', // Optional, defaults to driver's standard port
    // 'policy_table_name' => 'casbin_rules', // Optional, defaults to 'casbin_rule'
];

// Initialize the Adapter with the DBAL parameters array (without Redis)
$adapter = DatabaseAdapter::newAdapter($dbConnectionParams);
// Alternatively, using the constructor:
// $adapter = new DatabaseAdapter($dbConnectionParams);

// Option 2: Using an existing Doctrine DBAL Connection instance
// $dbalConnection = DriverManager::getConnection($dbConnectionParams);
// $adapter = DatabaseAdapter::newAdapter($dbalConnection);
// Or using the constructor:
// $adapter = new DatabaseAdapter($dbalConnection);

$e = new Enforcer('path/to/model.conf', $adapter);

$sub = "alice"; // the user that wants to access a resource.
$obj = "data1"; // the resource that is going to be accessed.
$act = "read"; // the operation that the user performs on the resource.

if ($e->enforce($sub, $obj, $act) === true) {
    // permit alice to read data1
} else {
    // deny the request, show an error
}
```

### Usage with Redis Caching

[](#usage-with-redis-caching)

To improve performance and reduce database load, the adapter supports caching policy data using [Redis](https://redis.io/). When enabled, Casbin policies will be fetched from Redis if available, falling back to the database if the cache is empty.

To enable Redis caching, provide a Redis configuration array as the second argument when initializing the adapter. The first argument remains your Doctrine DBAL connection (either a parameters array or a `Connection` object).

**Redis Configuration Options:**

- `host` (string): Hostname or IP address of the Redis server. Default: `'127.0.0.1'`.
- `port` (int): Port number of the Redis server. Default: `6379`.
- `password` (string, nullable): Password for Redis authentication. Default: `null`.
- `database` (int): Redis database index. Default: `0`.
- `ttl` (int): Cache Time-To-Live in seconds. Policies stored in Redis will expire after this duration. Default: `3600` (1 hour).
- `prefix` (string): Prefix for all Redis keys created by this adapter. Default: `'casbin_policies:'`.

**Example:**

```
require_once './vendor/autoload.php';

use Casbin\Enforcer;
use CasbinAdapter\DBAL\Adapter as DatabaseAdapter;
use Doctrine\DBAL\DriverManager; // Required if creating a new connection object

// Database connection parameters (can be an array or a Connection object)
$dbConnectionParams = [
    'driver' => 'pdo_mysql',
    'host' => '127.0.0.1',
    'dbname' => 'casbin_db',
    'user' => 'root',
    'password' => '',
    'port' => '3306',
];
// Example with DBAL connection object:
// $dbalConnection = DriverManager::getConnection($dbConnectionParams);

// Redis configuration
$redisConfig = [
    'host' => '127.0.0.1',      // Optional, defaults to '127.0.0.1'
    'port' => 6379,             // Optional, defaults to 6379
    'password' => null,         // Optional, defaults to null
    'database' => 0,            // Optional, defaults to 0
    'ttl' => 7200,              // Optional, Cache policies for 2 hours (default is 3600)
    'prefix' => 'myapp_casbin:' // Optional, Custom prefix (default is 'casbin_policies:')
];

// Initialize adapter with DB parameters array and Redis configuration
$adapter = DatabaseAdapter::newAdapter($dbConnectionParams, $redisConfig);
// Or, using a DBAL Connection object:
// $adapter = DatabaseAdapter::newAdapter($dbalConnection, $redisConfig);
// Alternatively, using the constructor:
// $adapter = new DatabaseAdapter($dbConnectionParams, $redisConfig);

$e = new Enforcer('path/to/model.conf', $adapter);

// ... rest of your Casbin usage
```

#### Cache Preheating

[](#cache-preheating)

The adapter provides a `preheatCache()` method to proactively load all policies from the database and store them in the Redis cache. This can be useful during application startup or as part of a scheduled task to ensure the cache is warm, reducing latency on initial policy checks.

**Example:**

```
if ($adapter->preheatCache()) {
    // Cache preheating was successful
    echo "Casbin policy cache preheated successfully.\n";
} else {
    // Cache preheating failed (e.g., Redis not available or DB error)
    echo "Casbin policy cache preheating failed.\n";
}
```

#### Cache Invalidation

[](#cache-invalidation)

The cache is designed to be automatically invalidated when policy-modifying methods are called on the adapter (e.g., `addPolicy()`, `removePolicy()`, `savePolicy()`, etc.). Currently, this primarily clears the cache key for all policies (`{$prefix}all_policies`).

**Important Note:** The automatic invalidation for *filtered policies* (policies loaded via `loadFilteredPolicy()`) is limited. Due to the way `predis/predis` client works and to avoid using performance-detrimental commands like `KEYS *` in production environments, the adapter does not automatically delete cache entries for specific filters by pattern. If you rely heavily on `loadFilteredPolicy` and make frequent policy changes, consider a lower TTL for your Redis cache or implement a more sophisticated cache invalidation strategy for filtered results outside of this adapter if needed. The main `{$prefix}all_policies` cache is cleared on any policy change, which means subsequent calls to `loadPolicy()` will refresh from the database and update this general cache.

### Getting Help

[](#getting-help)

- [php-casbin](https://github.com/php-casbin/php-casbin)

### License

[](#license)

This project is licensed under the [Apache 2.0 license](LICENSE).

###  Health Score

49

—

FairBetter than 94% of packages

Maintenance48

Moderate activity, may be stable

Popularity42

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 73.3% 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 ~162 days

Recently: every ~92 days

Total

14

Last Release

382d ago

Major Versions

v1.1.1 → v2.0.02020-12-16

v2.4.1 → v3.0.02024-10-29

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/35752209?v=4)[Jon](/maintainers/leeqvip)[@leeqvip](https://github.com/leeqvip)

---

Top Contributors

[![leeqvip](https://avatars.githubusercontent.com/u/35752209?v=4)](https://github.com/leeqvip "leeqvip (22 commits)")[![Dobmod](https://avatars.githubusercontent.com/u/33273950?v=4)](https://github.com/Dobmod "Dobmod (3 commits)")[![basakest](https://avatars.githubusercontent.com/u/47746206?v=4)](https://github.com/basakest "basakest (2 commits)")[![alonexy](https://avatars.githubusercontent.com/u/10362836?v=4)](https://github.com/alonexy "alonexy (1 commits)")[![Cryszon](https://avatars.githubusercontent.com/u/5220970?v=4)](https://github.com/Cryszon "Cryszon (1 commits)")[![tasselchof](https://avatars.githubusercontent.com/u/7921861?v=4)](https://github.com/tasselchof "tasselchof (1 commits)")

---

Tags

acladaptercasbindatabasedbalpermissionrbacdatabasedbaladapteraclpermissionrbaccasbin

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/casbin-dbal-adapter/health.svg)

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

###  Alternatives

[doctrine/doctrine-bundle

Symfony DoctrineBundle

4.8k254.4M4.1k](/packages/doctrine-doctrine-bundle)[doctrine/migrations

PHP Doctrine Migrations project offer additional functionality on top of the database abstraction layer (DBAL) for versioning your database schema and easily deploying changes to it. It is a very easy to use and a powerful tool.

4.8k217.3M547](/packages/doctrine-migrations)[martin-georgiev/postgresql-for-doctrine

Extends Doctrine with native PostgreSQL support for arrays, JSONB, ranges, PostGIS geometries, text search, ltree, uuid, and 100+ PostgreSQL-specific functions.

4585.8M4](/packages/martin-georgiev-postgresql-for-doctrine)[casbin/yii-permission

Use Casbin in Yii2 PHP Framework, Casbin is a powerful and efficient open-source access control library.

468.7k](/packages/casbin-yii-permission)[casbin/laravel-authz

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

331368.6k4](/packages/casbin-laravel-authz)[casbin/think-authz

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

27521.0k6](/packages/casbin-think-authz)

PHPackages © 2026

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