Skip to main content

Overview

The GAC class is the core entry point for the Granular Access Control library. It manages database and cache adapters, entity configuration, and provides methods to retrieve permissions and restrictions.

Constructor

The GAC class uses a fluent interface pattern for configuration. Initialize without parameters and chain configuration methods.
$gac = new GAC();

Configuration Methods

setDatabase()

Establishes database connection for GAC.
public function setDatabase(PDO|array|object $params): GAC
params
PDO|array|object
required
Database connection parameters. Can be:
  • PDO instance for direct PDO connection
  • array with connection parameters (passed to DatabaseAdapter)
  • Custom adapter implementing DatabaseAdapterInterface
return
GAC
Returns the GAC instance for method chaining
Throws: DatabaseAdapterException if invalid adapter provided
// Using PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$gac->setDatabase($pdo);

// Using array
$gac->setDatabase([
    'host' => 'localhost',
    'database' => 'mydb',
    'username' => 'user',
    'password' => 'pass'
]);

setCache()

Configures caching for permissions and restrictions.
public function setCache(
    string|null $key = null,
    string|int|null $ttl = null,
    string|object $dir = null
): GAC
key
string|null
default:"gac"
Cache key prefix for stored data
ttl
string|int|null
default:"1800"
Time to live in seconds (default: 30 minutes)
dir
string|object
default:"__DIR__ . '/writable'"
Cache directory path or custom adapter implementing CacheAdapterInterface
return
GAC
Returns the GAC instance for method chaining
Throws: CacheAdapterException if invalid adapter provided
// Using default file cache
$gac->setCache('my_app', 3600, '/var/cache/gac');

// Using custom adapter
$redisAdapter = new RedisCacheAdapter($redisClient);
$gac->setCache('my_app', 3600, $redisAdapter);

setEntity()

Sets the entity (user or client) for permission/restriction queries.
public function setEntity(string $entityType, string|int $entityId): GAC
entityType
string
required
Entity type: 'user', 'client', or numeric type key ('1', '2')
entityId
string|int
required
Unique identifier for the entity
return
GAC
Returns the GAC instance for method chaining
// Set user entity
$gac->setEntity('user', 123);

// Set client entity
$gac->setEntity('client', 'abc-456');

setCacheTtl()

Sets the cache time-to-live value.
public function setCacheTtl(int $ttl): GAC
ttl
int
required
Cache lifetime in seconds
return
GAC
Returns the GAC instance for method chaining
$gac->setCacheTtl(7200); // 2 hours

setCacheKey()

Sets the cache key prefix.
public function setCacheKey(string $prefix): GAC
prefix
string
required
Prefix for all cache keys
return
GAC
Returns the GAC instance for method chaining
$gac->setCacheKey('app_v2');

Data Retrieval Methods

getPermissions()

Retrieves permissions for the configured entity.
public function getPermissions(bool $fromCache = true): Permissions
fromCache
bool
default:"true"
Whether to attempt loading from cache before querying database
return
Permissions
Permissions instance containing all module access permissions
Throws: Exception if entity type and ID not set
$permissions = $gac->setEntity('user', 123)->getPermissions();

if ($permissions->has('invoices')) {
    $invoice = $permissions->get('invoices');
    if ($invoice->hasFeature('create')) {
        // User can create invoices
    }
}

getRestrictions()

Retrieves restrictions for the configured entity.
public function getRestrictions(bool $fromCache = true): Restrictions
fromCache
bool
default:"true"
Whether to attempt loading from cache before querying database
return
Restrictions
Restrictions instance containing all active restrictions
Throws: Exception if entity type and ID not set
$restrictions = $gac->setEntity('user', 123)->getRestrictions();

if ($restrictions->has('by_date')) {
    $dateRestriction = $restrictions->get('by_date');
    $isAllowed = $dateRestriction->run(['date' => time()]);
}

Cache Management Methods

clearCache()

Clears cached permissions and restrictions for the current entity.
public function clearCache(bool $includeGlobal = false): bool
includeGlobal
bool
default:"false"
Whether to also clear global restrictions cache
return
bool
Returns true on success, false on failure
Throws: CacheAdapterException if cache adapter not set
// Clear user's cache
$gac->setEntity('user', 123)->clearCache();

// Clear including global restrictions
$gac->setEntity('user', 123)->clearCache(true);

purgePermissionsBy()

Purges permissions cache by entity criteria.
public function purgePermissionsBy(string $entityType, array $entityIds = []): bool
entityType
string
required
Entity type: 'user', 'client', 'role', or 'global'
entityIds
array
default:"[]"
Array of entity IDs to purge. Required unless entityType is 'global'
return
bool
Returns true on success, false if no IDs provided for non-global purge
// Purge specific users
$gac->purgePermissionsBy('user', [123, 456, 789]);

// Purge all users with a specific role
$gac->purgePermissionsBy('role', [5]);

// Purge all entities
$gac->purgePermissionsBy('global');

purgeRestrictionsBy()

Purges restrictions cache by entity criteria.
public function purgeRestrictionsBy(string $entityType, array $entityIds = []): bool
entityType
string
required
Entity type: 'user', 'client', 'role', or 'global'
entityIds
array
default:"[]"
Array of entity IDs to purge. Required unless entityType is 'global'
return
bool
Returns true on success, false if no IDs provided for non-global purge
// Purge specific clients
$gac->purgeRestrictionsBy('client', ['abc-123', 'def-456']);

// Purge all clients with a specific role
$gac->purgeRestrictionsBy('role', [3, 4]);

Getter Methods

getEntityType()

Returns the configured entity type.
public function getEntityType(): string
return
string
The entity type key ('1' for user, '2' for client)

getEntityId()

Returns the configured entity ID.
public function getEntityId(): string|int
return
string|int
The entity identifier

getCacheKey()

Generates cache key for a given type.
public function getCacheKey(string $type): string
type
string
required
Type of cache: 'permissions', 'restrictions', or 'restrictions_global'
return
string
Generated cache key

getEntityRoleData()

Retrieves role data for the current entity.
public function getEntityRoleData(bool $reset = false): array
reset
bool
default:"false"
Force reload from database
return
array
Array with 'list' (role IDs) and 'priority' (role priorities) keys

Complete Usage Example

use DancasDev\GAC\GAC;

// Initialize and configure
$gac = new GAC();
$gac->setDatabase($pdo)
    ->setCache('my_app', 3600)
    ->setEntity('user', 123);

// Get and check permissions
$permissions = $gac->getPermissions();
if ($permissions->has('products')) {
    $product = $permissions->get('products');
    
    if ($product->hasFeature(['read', 'update'])) {
        // User can read and update products
        echo "Access level: " . $product->getLevel();
    }
}

// Get and validate restrictions
$restrictions = $gac->getRestrictions();
if ($restrictions->has('by_date')) {
    $dateRestriction = $restrictions->get('by_date');
    $canAccess = $dateRestriction->run(['date' => time()]);
    
    if (!$canAccess) {
        echo "Access denied by date restriction";
    }
}

// Clear cache when permissions change
$gac->clearCache();

Public Properties

databaseAdapter
DatabaseAdapter|object
The configured database adapter instance
cacheAdapter
CacheAdapter|object
The configured cache adapter instance

See Also

Build docs developers (and LLMs) love