PHP code example of caridea / acl

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

    

caridea / acl example snippets


class MyLoader implements \Caridea\Acl\Loader
{
    public function supports(Target $target)
    {
        return $target->getType() == 'foobar';
    }

    public function load(Target $target, array $subjects, Service $service)
    {
        // some custom method to load my database record
        try {
            $record = MyRecord::loadFromDatabase($target->getId());
        } catch (\Exception $e) {
            throw new \Caridea\Acl\Exception\Unloadable("Could not load record", 0, $e);
        }
        // load the parent record's ACL
        $parent = $service->get(new Target('foobar', $record['parent']), $subjects);
        // create the rules and return the final constructed ACL
        $rules = [];
        foreach ($subjects as $subject) {
            if ($subject->getType() == 'role' &&
                $subject->getId() == 'admin') {
                // allow "admin" role for all permissions
                $rules[] = Rule::allow($subject);
            } elseif ($subject->getType() == 'role' &&
                $subject->getId() == 'user') {
                // allow "user" role the read permission
                $rules[] = Rule::allow($subject, ['read']);
            } elseif ($subject->getType() == 'principal' &&
                $subject->getId() == $record['owner']) {
                // allow the record owner CRUD permissions
                $rules[] = Rule::allow($subject, ['create', 'read', 'update', 'delete']);
            }
        }
        return new RuleAcl($target, $subjects, $rules, $parent);
    }
}

// A list of all of your custom loaders
$loaders = [new MyLoader()];
// Use the Cache Strategy to cache lookups
$strategy = new \Caridea\Acl\CacheStrategy(
    new \Caridea\Acl\DelegateStrategy($loaders);
);
$service = new \Caridea\Acl\Service($strategy);

$subjects = MyClass::getSubjects(); // determine which subjects the user has
$target = new Target('foobar', 123);

$allowed = $service->can($subjects, 'delete', $target);

try {
    $service->assert($subjects, 'delete', $target);
} catch (\Caridea\Acl\Exception\Forbidden $e) {
    // not allowed!
}