角色类模型正确实现

时间:2012-03-14 10:00:36

标签: php design-patterns model role

我一直在尝试将角色类模型模式实现到我的网站用户访问机制(用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($用户);

  3. 我可能在这里缺少必要的东西。你们能否对这个问题有所了解,好吗?

1 个答案:

答案 0 :(得分: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');

以下是User对象与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.')
}
相关问题