2012-03-14 212 views
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. 传递任何其他$用户> uid解释为“SomethingAdminish”方法将在我的日志 日志信息不正确系统(错误的用户ID)
  2. 如果我决定在上述方法中登录其他用户信息, 基本上我将不得不通过整个用户对象作为参数, 像这样:

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

我可能错过了这里必不可少的东西。请你们介绍一下这个问题?

回答

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.') 
} 
互动