2

我一直在尝试为我的网站用户访问机制(用 PHP 编写)实现角色类模型模式。不过我有一些疑问。以下是相关代码的简化版本:

class User 
{
        public $role;
        public $uid;        
        public function setRole($role)
        {
            $this->role = $role;
        }
} 
// role classes responsible for restricted actions
class BaseRole {} 
class AdminRole extends BaseRole
{ 
       // do something adminish + log action into database (with User ID)
       public function SomethingAdminish($admin_id) { }
}
$user = new User();
$user->setRole(new AdminRole());

// pass Admin ID (User ID) into method
$user->rola->SomethingAdminish($user->uid);

我在这里看到了一些弱点:

  1. 将任何其他 $user->uid 传递给“SomethingAdminish”方法会将不正确的信息记录到我的日志系统中(错误的用户 ID)
  2. 如果我决定在上述方法中记录其他用户信息,基本上我必须将整个用户对象作为参数传递,如下所示:

    $user->rola->SomethingAdminish($user);

我可能在这里遗漏了一些重要的东西。请问各位大神,能不能给点思路?

4

1 回答 1

0

我个人会设置并使用访问控制列表 (ACL) 模式。

“资源是访问受到控制的对象。

角色是可以请求访问资源的对象。

简而言之,角色请求访问资源。例如,如果停车服务员请求访问汽车,则停车服务员是请求角色,而汽车是资源,因为可能不会向所有人授予对汽车的访问权限。”

这是 ACL 流外观的基本示例(使用上面的代码)。

// Create an ACL object to store roles and resources. The ACL also grants
// and denys access to resources.
$acl = new Acl();

// Create 2 roles. 
$adminRole = new Acl_Role('admin');
$editorRole = new Acl_Role('editor');

// Add the Roles to the ACL.
$acl->addRole($adminRole)
    ->addRole($editorRole);

// Create an example Resource. A somethingAdminish() function in this case.
$exampleResource = new Acl_Resource('somethingAdminish');

// Add the Resource to the ACL.
$acl->add($exampleResource);

// Define the rules. admins can are allowed access to the somethingAdminish
// resource, editors are denied access to the somethingAdminish resource.
$acl->allow('admin', 'somethingAdminish');
$acl->deny('editor', 'somethingAdminish');

以下是用户对象如何与 ACL 交互

// Load the User
$userID = 7;
$user = User::load($userID);

// Set the User's Role. admin in this case.
$user->setRole($adminRole);

// Query the ACL to see if this User can access the somethingAdminish resource.
if ($acl->isAllowed($user, 'somethingAdminish')){

    // Call the somethingAdminish function. Eg:
    somethingAdminish();

    // Log the action and pass the User object in so you can take any information
    // you require from the User data.
    $acl->logAction('somethingAdminish', $user)

}else{
    die('You dont have permission to perform the somethingAdminish action.')
}
于 2013-04-03T12:36:58.947 回答