yiisoft/rbac-cycle-db 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

yiisoft/rbac-cycle-db

Composer 安装命令:

composer require yiisoft/rbac-cycle-db

包简介

Yii RBAC Cycle Database storage

README 文档

README

Yii

Yii RBAC Cycle Database


Latest Stable Version Total Downloads codecov Mutation testing badge static analysis type-coverage

The package provides Cycle Database storage for Yii RBAC.

Detailed build statuses:

RDBMS Status
SQLite SQLite status
MySQL MYSQL status
PostgreSQL PostgreSQL status
Microsoft SQL Server Microsoft SQL Server status

Requirements

  • PHP 8.1 or higher.
  • In the case of using with SQLite, a minimal required version is 3.8.3.
  • In the case of using with SQL Server, a minimal required version of PDO is 5.11.1.

Installation

The package could be installed with composer:

composer require yiisoft/rbac-cycle-db

General usage

Configuring database connection

Configuration depends on a selected driver. Here is an example for PostgreSQL:

use Cycle\Database\Config\DatabaseConfig;
use Cycle\Database\Config\Postgres\DsnConnectionConfig;
use Cycle\Database\Config\PostgresDriverConfig;
use Cycle\Database\DatabaseManager;

$dbConfig = new DatabaseConfig(
    [
        'default' => 'default',
        'databases' => [
            'default' => ['connection' => 'pgsql'],
        ],
        'connections' => [
            'pgsql' => new PostgresDriverConfig(new DsnConnectionConfig(
                'pgsql:host=127.0.0.1;dbname=yiitest;port=5432',
                'user',
                'password',
            )),
        ],
    ]
);
$databaseManager = new DatabaseManager($dbConfig);
$database = $databaseManager->database();

More comprehensive examples can be found at Cycle Database docs.

Working with migrations

This package uses Cycle Migrations for managing database tables required for storages. There are three tables in total (yii_rbac_ prefix is used).

Items storage:

  • yii_rbac_item.
  • yii_rbac_item_child.

Assignments storage:

  • yii_rbac_assignment.

Configuring migrator and capsule

use Cycle\Database\DatabaseManager;
use Cycle\Migrations\Capsule;
use Cycle\Migrations\Config\MigrationConfig;
use Cycle\Migrations\FileRepository;
use Cycle\Migrations\Migrator;

$migrationsSubfolders = ['items', 'assignments'];
$directories = array_map(
    static fn (): string => dirname(__DIR__. 2),  "/vendor/yiisoft/rbac-cycle-db/migrations/$subfolder",
    $migrationsSubfolders, 
);
$config = new MigrationConfig([
    'directory' => $directories[0],
    // "vendorDirectories" are specified because the "directory" option doesn't support multiple directories. In the
    // end, it makes no difference because they all will be merged into a single array.
    'vendorDirectories' => $directories[1] ?? [],
    'table' => 'cycle_migration',
    'safe' => true,
]);
/** @var DatabaseManager $databaseManager */
$migrator = new Migrator($config, $databaseManager, new FileRepository($config));
$migrator->configure();

$capsule = new Capsule($databaseManager->database());

For configuring $databaseManager, see previous section.

Because item and assignment storages are completely independent, migrations are separated as well to prevent the creation of unused tables. So, for example, if you only want to use assignment storage, adjust $migrationsSubfolders variable like this:

$migrationsSubfolders = ['assignments'];

Applying migrations

use Cycle\Migrations\Capsule;
use Cycle\Migrations\Migrator;

/**
 * @var Migrator $migrator
 * @var Capsule $capsule 
 */
while ($migrator->run($capsule) !== null) {
    echo "Migration {$migration->getState()->getName()} applied successfully.\n";
}

Reverting migrations

use Cycle\Migrations\Capsule;
use Cycle\Migrations\Migrator;

/**
 * @var Migrator $migrator
 * @var Capsule $capsule 
 */
while ($migrator->rollback($capsule) !== null) {
    echo "Migration {$migration->getState()->getName()} reverted successfully.\n";
}

Using storages

The storages are not intended to be used directly. Instead, use them with Manager from Yii RBAC package:

use Cycle\Database\DatabaseInterface;
use Yiisoft\Rbac\Cycle\AssignmentsStorage;
use Yiisoft\Rbac\Cycle\ItemsStorage;
use Yiisoft\Rbac\Cycle\TransactionalManagerDecorator;
use Yiisoft\Rbac\Manager;
use Yiisoft\Rbac\Permission;
use Yiisoft\Rbac\RuleFactoryInterface;

/** @var DatabaseInterface $database */
$itemsStorage = new ItemsStorage($database);
$assignmentsStorage = new AssignmentsStorage($database);
/** @var RuleFactoryInterface $rulesContainer */
$manager = new TransactionalManagerDecorator(
    new Manager(
        itemsStorage: $itemsStorage, 
        assignmentsStorage: $assignmentsStorage,
        // Requires https://github.com/yiisoft/rbac-rules-container or another compatible factory.
        ruleFactory: $rulesContainer,
    ),
);
$manager->addPermission(new Permission('posts.create'));

Note wrapping manager with decorator—it additionally provides database transactions to guarantee data integrity.

Note that it's not necessary to use both DB storages. Combining different implementations is possible. A quite popular case is to manage items via PHP file while store assignments in a database.

More examples can be found in Yii RBAC documentation.

Syncing storages manually

The storages stay synced thanks to manager, but there can be situations where you need to sync them manually. One of them is using combination with PHP file based storage and editing it manually.

Let's say PHP file is used for items, while database - for assignments, and some items were deleted:

return [
    [
        'name' => 'posts.admin',        
        'type' => 'role',        
        'created_at' => 1683707079,
        'updated_at' => 1683707079,
        'children' => [
            'posts.redactor',
            'posts.delete',
            'posts.update.all',
        ],
    ],
-   [
-       'name' => 'posts.redactor',
-       'type' => 'role',        
-       'created_at' => 1683707079,
-       'updated_at' => 1683707079,
-       'children' => [
-           'posts.viewer',
-           'posts.create',
-           'posts.update',
-       ],
-   ],
    [
        'name' => 'posts.viewer',
        'type' => 'role',        
        'created_at' => 1683707079,
        'updated_at' => 1683707079,
        'children' => [
            'posts.view',
        ],
    ],
    [
        'name' => 'posts.view',
        'type' => 'permission',        
        'created_at' => 1683707079,
        'updated_at' => 1683707079,
    ],
    [
        'name' => 'posts.create',
        'type' => 'permission',        
        'created_at' => 1683707079,
        'updated_at' => 1683707079,
    ],
-   [
-       'name' => 'posts.update',
-       'rule_name' => 'is_author',
-       'type' => 'permission',
-       'created_at' => 1683707079,
-       'updated_at' => 1683707079,
-   ],
    [
        'name' => 'posts.delete',        
        'type' => 'permission',        
        'created_at' => 1683707079,
        'updated_at' => 1683707079,
    ],
    [
        'name' => 'posts.update.all',
        'type' => 'permission',        
        'created_at' => 1683707079,
        'updated_at' => 1683707079,
    ],
];

Then related entries in other storage needs to be deleted as well. This can be done within a migration:

use Cycle\Migrations\Migration;

final class DeletePostUpdateItems extends Migration
{
    private const TABLE_PREFIX = 'yii_rbac_';
    private const ASSIGNMENTS_TABLE = self::TABLE_PREFIX . 'assignment';

    public function up()
    {
        $this
            ->database()
            ->delete()
            ->from(self::ASSIGNMENTS_TABLE)
            ->where('item_name', 'IN', ['posts.redactor', 'posts.update']);
    }

    public function down()
    {
    }
}

Documentation

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

License

The Yii RBAC Cycle Database is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

yiisoft/rbac-cycle-db 适用场景与选型建议

yiisoft/rbac-cycle-db 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 31.05k 次下载、GitHub Stars 达 17, 最近一次更新时间为 2022 年 02 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「storage」 「yii」 「rbac」 「cycle」 「cycle-db」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 yiisoft/rbac-cycle-db 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 yiisoft/rbac-cycle-db 我们能提供哪些服务?
定制开发 / 二次开发

基于 yiisoft/rbac-cycle-db 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 31.05k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 17
  • 点击次数: 21
  • 依赖项目数: 1
  • 推荐数: 1

GitHub 信息

  • Stars: 17
  • Watchers: 13
  • Forks: 7
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2022-02-20