PHP code example of casbin / easyswoole-permission

1. Go to this page and download the library: Download casbin/easyswoole-permission 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/ */

    

casbin / easyswoole-permission example snippets


/*################ MYSQL CONFIG ##################*/

'MYSQL'  => [
    'host'          => '127.0.0.1',
    'port'          => 3306,
    'user'          => 'root',
    'password'      => 'root',
    'database'      => 'easyswoole',
    'timeout'       => 5,
    'charset'       => 'utf8mb4',
]

use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\DbManager;

public static function initialize()
{
  ...
  $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));
  DbManager::getInstance()->addConnection(new Connection($config));
}

use EasySwoole\Permission\Casbin;
use EasySwoole\Permission\Config;

$config = new Config();
$casbin = new Casbin($config);

// adds permissions to a user
$casbin->addPermissionForUser('eve', 'articles', 'read');
// adds a role for a user.
$casbin->addRoleForUser('eve', 'writer');
// adds permissions to a rule
$casbin->addPolicy('writer', 'articles', 'edit');

// to check if a user has permission
if ($casbin->enforce('eve', 'articles', 'edit')) {
  // permit eve to edit articles
} else {
  // deny the request, show an error
}

$config = new Config();
$casbin = new Casbin($config);
$enforcer = $casbin->enforcer();

$enforcer->getAllRoles(); // ['writer', 'reader']

$enforcer->getPolicy();

$enforcer->getRolesForUser('eve'); // ['writer']

$enforcer->getUsersForRole('writer'); // ['eve']

$enforcer->hasRoleForUser('eve', 'writer'); // true or false

$enforcer->addRoleForUser('eve', 'writer');

// to user
$enforcer->addPermissionForUser('eve', 'articles', 'read');
// to role
$enforcer->addPermissionForUser('writer', 'articles','edit');

$enforcer->deleteRoleForUser('eve', 'writer');

$enforcer->deleteRolesForUser('eve');

$enforcer->deleteRole('writer');

$enforcer->deletePermission('articles', 'read'); // returns false if the permission does not exist (aka not affected).

$enforcer->deletePermissionForUser('eve', 'articles', 'read');

// to user
$enforcer->deletePermissionsForUser('eve');
// to role
$enforcer->deletePermissionsForUser('writer');

$enforcer->getPermissionsForUser('eve'); // return array

$enforcer->hasPermissionForUser('eve', 'articles', 'read');  // true or false