物件作為角色和資源

通過實現 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 方法中的附加條件和使用物件時,你不需要將這些物件作為引數傳遞。只有在函式中的引數之前有正確的型別時,它們才會自動傳遞。這使你能夠控制某些使用者是否可以編輯應用程式中的某些模型以及何時可以執行此操作。