將每個權限定義為 **2 的 N 次方**(二進制只有一個 1),通過位或 | 組合、位與 & 判斷、位非 ~ 移除實現高效權限運算。
define('PERM_ADD', 1); // 0001
define('PERM_EDIT', 2); // 0010
define('PERM_VIEW', 4); // 0100
define('PERM_DEL', 8); // 1000
// 賦予權限:位或 |
$adminPerm = PERM_ADD | PERM_EDIT | PERM_VIEW | PERM_DEL; // 1111 = 15
$editorPerm = PERM_ADD | PERM_EDIT | PERM_VIEW; // 0111 = 7
$viewerPerm = PERM_VIEW; // 0100 = 4
// 移除權限:位與 + 位非 &= ~
$editorNoDel = $editorPerm & ~PERM_DEL; // 0111 & 0111 = 0111 (原本無 DEL 無變化)
$adminNoEdit = $adminPerm & ~PERM_EDIT; // 1111 & 1101 = 1101 = 13
// 判斷權限:位與 &
var_dump($editorPerm & PERM_ADD); // int(1) -> true 擁有
var_dump($editorPerm & PERM_DEL); // int(0) -> false 無權限
Auth 與角色類 Role<?php
/** 簡單權限類:自動生成 2^N 權限值 */
class Auth {
private static int $counter = 0;
public string $name;
public string $desc;
public int $value;
public function __construct(string $name, string $desc = '') {
$this->name = $name;
$this->desc = $desc;
$this->value = 1 << self::$counter++; // 1, 2, 4, 8...
}
public function getValue(): int { return $this->value; }
}
/** 角色類:支持繼承父角色權限、鏈式調用 */
class Role {
public string $name;
private int $permBits = 0;
private ?Role $parent = null;
public function __construct(string $name, ?Role $parent = null) {
$this->name = $name;
$this->parent = $parent;
if ($parent) $this->permBits = $parent->getPermBits();
}
private function getPermBits(): int { return $this->permBits; }
/** 賦予權限 */
public function allow(Auth $auth): self {
$this->permBits |= $auth->getValue();
return $this;
}
/** 移除權限 */
public function deny(Auth $auth): self {
$this->permBits &= ~$auth->getValue();
return $this;
}
/** 檢查權限 */
public function can(Auth $auth): bool {
return ($this->permBits & $auth->getValue()) !== 0;
}
public function getPermBitsPublic(): int { return $this->permBits; }
}
// 定義權限
$read = new Auth('READ', '讀取');
$write = new Auth('WRITE', '寫入');
$exec = new Auth('EXEC', '執行');
$admin = new Auth('ADMIN', '管理');
// 角色體系
$guest = new Role('Guest');
$user = new Role('User', $guest); // 繼承 Guest
$adminRole = new Role('Admin', $user); // 繼承 User -> Guest
// 賦予權限
$guest->allow($read);
$user->allow($write);
$adminRole->allow($exec)->allow($admin);
// 移除權限(管理員不需要寫入?示例)
$adminRole->deny($write);
// 檢查
var_dump($adminRole->can($read)); // true (繼承自 Guest)
var_dump($adminRole->can($write)); // false (被 deny)
var_dump($adminRole->can($exec)); // true
var_dump($adminRole->can($admin)); // true
roles 表:id, name, parent_id, perm_bits (BIGINT UNSIGNED)permissions 表:id, name, bit_value (INT UNSIGNED), descriptionSELECT perm_bits FROM roles WHERE id = ?(含繼承已合併)。WHERE (perm_bits & 4) > 0。| 優點 | 缺點 |
|---|---|
| 極高性能(位運算 CPU 指令級) | 權限數量受限於整型位數(64位系統最多 64 權限) |
| 存儲極緊湊(單 BIGINT) | 權限語義不直觀,需常量/文檔維護 |
| 組合/判斷/繼承代碼極簡潔 | 不支持「上下文相關權限」(如「僅編輯自己發布的文章」) |
| 天然支持角色繼承(位或合併父權限) | 動態權限(運行時計算)難以直接映射 |
適用: 後台管理、CMS、API 權限、功能開關等**靜態、枚舉型、數量<64**的權限體系。
不適用: 基於資源所有者、屬性、關係的動態權限(ABAC),請用 Casbin/PHP-Casbin 等策略引擎。