PHP code example of yiisoft / rbac-db

1. Go to this page and download the library: Download yiisoft/rbac-db library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yiisoft / rbac-db example snippets


use Yiisoft\Cache\ArrayCache; // Requires https://github.com/yiisoft/cache
use Yiisoft\Db\Cache\SchemaCache;
use Yiisoft\Db\Pgsql\Connection;
use Yiisoft\Db\Pgsql\Driver;

$pdoDriver = new Driver('pgsql:host=127.0.0.1;dbname=yiitest;port=5432', 'user', 'password');
$pdoDriver->charset('UTF8');
$connection = Connection(
    $pdoDriver, 
    new SchemaCache(
        new ArrayCache(), // Any other PSR-16 compatible cache can be used.
    )
);

'yiisoft/db-migration' => [
    // ...
    'sourcePaths' => [
        dirname(__DIR__) . '/vendor/yiisoft/rbac-db/migrations/items',
        dirname(__DIR__) . '/vendor/yiisoft/rbac-db/migrations/assignments',
    ],
],



declare(strict_types=1);

use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Pgsql\Connection as PgsqlConnection;

return [
    ConnectionInterface::class => [
        'class' => PgsqlConnection::class,
        '__construct()' => [
            // ...
        ],
    ]
];

use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Rbac\Db\AssignmentsStorage;
use Yiisoft\Rbac\Db\ItemsStorage;
use Yiisoft\Rbac\Db\TransactionalManagerDecorator;
use Yiisoft\Rbac\Manager;
use Yiisoft\Rbac\Permission;
use Yiisoft\Rbac\RuleFactoryInterface;

/** @var ConnectionInterface $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'));

use Yiisoft\Db\Migration\MigrationBuilder;
use Yiisoft\Db\Migration\RevertibleMigrationInterface;
use Yiisoft\Db\Migration\TransactionalMigrationInterface;

final class M240229184400DeletePostUpdateItems implements RevertibleMigrationInterface, TransactionalMigrationInterface
{
    private const TABLE_PREFIX = 'yii_rbac_';
    private const ASSIGNMENTS_TABLE = self::TABLE_PREFIX . 'assignment';
    
    public function up(MigrationBuilder $b): void
    {
        $b
            ->getDb()
            ->createCommand()
            ->delete(self::ASSIGNMENTS_TABLE, ['item_name' => ['posts.redactor', 'posts.update']])
            ->execute();
    }
    
    public function down(MigrationBuilder $b): void; 
    {        
    }   
}

./vendor/bin/phpunit

./vendor/bin/infection

./vendor/bin/psalm