对象作为角色和资源

通过实现 Phalcon\Acl\RoleAwarePhalcon\Acl\ResourceAware,你可以将它们用作 Phalcon\Acl\Adapter\Memory::isAllowed() 中的对象。

// Create our class which will be used as roleName
class UserRole implements Phalcon\Acl\RoleAware
{
    protected $id;
    protected $roleName;

    public function __construct($id, $roleName)
    {
        $this->id = $id;
        $this->roleName = $roleName;
    }

    public function getId()
    {
        return $this->id;
    }

    // Implemented function from RoleAware Interface
    public function getRoleName()
    {
        return $this->roleName;
    }
}
// Create our class which will be used as resourceName
class ModelResource implements Phalcon\Acl\ResourceAware
{
    protected $id;
    protected $resourceName;
    protected $userId;

    public function __construct($id, $resourceName, $userId)
    {
        $this->id = $id;
        $this->resourceName = $resourceName;
        $this->userId = $userId;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getUserId()
    {
        return $this->userId;
    }

    // Implemented function from ResourceAware Interface
    public function getResourceName()
    {
        return $this->resourceName;
    }
}
$customer = new ModelResource(1, "products", 2);
$administrator = new UserRole(1, "Administrator");
$acl->isAllowed($administrator, $customer, 'create');

使用对象的能力也可以与 acl 中的附加条件组合:

$acl->allow('Administrator', 'products', 'update', function(UserRole $user, ModelResource $model) {
    return $user->getId == $model->getUserId();
});
$product = new ModelResource(1, 'products', 2);
$administrator = new UserRole(1, 'Administrator');
$anotherAdministrator = new UserRole(2, 'Administrator');
$acl->isAllowed($administrator, $product, 'update'); // this will return false
$acl->isAllowed($anotherAdministrator, $product, 'update'); // this will return true

请注意,使用 isAllowed 方法中的附加条件和使用对象时,你不需要将这些对象作为参数传递。只有在函数中的参数之前有正确的类型时,它们才会自动传递。这使你能够控制某些用户是否可以编辑应用程序中的某些模型以及何时可以执行此操作。