PHP code example of yiisoft / rbac-rules-container

1. Go to this page and download the library: Download yiisoft/rbac-rules-container 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-rules-container example snippets


use Psr\Container\ContainerInterface;
use Yiisoft\Rbac\Item;
use Yiisoft\Rbac\RuleInterface;
use Yiisoft\Rbac\Rules\Container\RulesContainer;

/**
 * Checks if user ID matches `authorID` passed via parameters.
 */
final class AuthorRule implements RuleInterface
{
    public function execute(string $userId, Item $item, array $parameters = []): bool
    {
        return $parameters['authorID'] === $userId;
    }
}

$rulesContainer = new RulesContainer(new MyContainer());
$rule = $rulesContainer->create(AuthorRule::class);

$rule = $rulesContainer->create(AuthorRule::class); // Returned from cache

use Yiisoft\Di\Container;
use Yiisoft\Di\ContainerConfig;
use Yiisoft\Rbac\RuleFactoryInterface;
use Yiisoft\Rbac\Rules\Container\RulesContainer;

// Need to be moved to separate files accordingly
$params = [
    'yiisoft/rbac-rules-container' => [
        'rules' => ['author' => AuthorRule::class],
        'validate' => false,
    ],
];
$config = [
    RuleFactoryInterface::class => [
        'class' => RulesContainer::class,
        '__construct()' => [
            'definitions' => $params['yiisoft/rbac-rules-container']['rules'],
            'validate' => $params['yiisoft/rbac-rules-container']['validate'],
        ],
    ],
];          
$containerConfig = ContainerConfig::create()->withDefinitions($config); 
$container = new Container($containerConfig);
$rulesContainer = $container->get(RuleFactoryInterface::class);        
$rule = $rulesContainer->create('author');