2012-03-14 208 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.') 
} 
互動