【问题标题】:Role Class Model correct implementation角色类模型正确实现
【发布时间】:2012-03-30 18:38:19
【问题描述】:

我一直在尝试为我的网站用户访问机制(用 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 对象作为参数传递, 像这样:

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

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

【问题讨论】:

    标签: php design-patterns model role


    【解决方案1】:

    我个人会设置并使用访问控制列表 (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.')
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 2018-05-27
      • 2011-10-16
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多