Skip to content
Permalink
master
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time

Privileges

The Privileges class manages user authorization.

Installation

composer require webiik/privileges

Example

$privileges = new \Webiik\Privileges\Privileges();

// Add roles
$privileges->addRole('user');
$privileges->addRole('admin');

// Add resources
$privileges->addResource('article', ['create', 'read', 'update', 'delete']);

// Allow access to resources
$privileges->allow('user', 'article', ['read']);
$privileges->allow('admin', 'article', ['all']);

// Test access to resources
if ($privileges->isAllowed('admin', 'article', 'update')) {
    // Admin can update an article
}

Adding Roles and Resources

addRole

addRole(string $role): void

addRole() adds user role.

$privileges->addRole('user');

addResource

addResource(string $resource, array $privileges): void

addResource() adds resource and supported resource privileges. Never set privilege 'all', resource will be not added.

$privileges->addResource('article', ['create', 'read', 'update', 'delete']);

Allowing Access to Resources

allow

allow(string $role, string $resource, array $privileges): void

allow() allows role access to the resource with given privileges. If role, resource or one of privileges doesn't exist, rule will be not added. If you want to grant all privileges, set privileges to ['all'].

$privileges->allow('user', 'article', ['read']);

Checking Access to Resources

isAllowed

isAllowed(string $role, string $resource, string $privilege): bool

isAllowed() checks if user with role can do privilege on resource.

if ($privileges->isAllowed('user', 'article', 'read')) {
    // User can read an article
}

Resources