webiik / privileges
The Privileges class manages user authorization.
1.0
2019-03-28 17:39 UTC
Requires
- php: >=7.2
This package is auto-updated.
Last update: 2025-01-29 06:31:30 UTC
README
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 }