3

Each object represents one row in the database. Example:

admins table

id, first_name, last_name
1, 'John', 'Doe'

$admin object (pseudo)

class admin extends base {
  protected $id;
  protected $first_name;
  protected $last_name;

  public function setter() { }

  public function getter() { }

  /* ETC */
}

This part is really clear to me, I can set, get and save (this function is located in base class) the data.

Now what should I do when I create a table that has multiple rows that are related to another table. Example:

admin_preveleges table

id, admin_id, privilege, value
1, 1, 'read_reports', 1
2, 1, 'delete_news', 1
3, 1, 'delete_users', 1

What would the object look? Would one object contain all 3 rows for our John Doe admin? Or would I create 3 objects for John Doe?

How can I connect these to the admin object?

If I create 3 separate objects and connect them to the $admin object, how could I check if this admin has the privilege do delete users? Would I have to loop through all objects and check if one of them is 'delete_users' and then break the loop?

Or should I forget about making the privilege table an object and just create a handler for it inside $admin object?

4

2 回答 2

1

由于一个管理员可以拥有许多特权,并且同一个特权可以属于多个管理员,我认为这是一种多对多的关系。我将创建一个包含 AdminID 和 PrivilageId 的第三个表,并且谁具有由这两个组成的组合主键。当您想将权限分配给 Admin 时,您必须在 PrivilageDetails 表中添加一个新行,其中包含要向其添加权限的 AdminId (PrivilageId)。如果您想查看哪些权限有管理员,您只需在这些表之间进行连接 在此处输入图像描述

于 2013-11-03T15:40:06.157 回答
1

创建一个新类AdminPrivilege

class AdminPrivilege extends base {
  protected $id;
  protected $admin_id;
  protected $privlege;
  protected $allowed;

  public function setter() { }

  public function getter() { }

  /* ETC */
}

然后在您的控制器类中创建一个名为loadAdminPrivilegesByAdminID($adminID). 在此方法中,为管理员加载权限,创建AdminPrivilege对象并将它们作为数组返回并将数组附加到您的admin对象。

class admin extends base {
  protected $id;
  protected $first_name;
  protected $last_name;
  protected $privileges; // NEW to attach the privileges of this admin to himself

  public function setter() { }

  public function getter() { }

  public function setPrivileges(array $privileges) {
    $this->privileges = $privileges;
  }

  public function getPrivileges() { 
    return $this->privileges;
  }

  /* ETC */
}

检查管理员是否具有特定权限很容易。在您的控制器类中创建一个新方法checkPrivilege($adminObj, $privilegeName)

public function checkPrivilege($adminObj, $privilegeName) {
  foreach($adminObj->getPrivileges() as $prv) {
    if($prv->privilege != $privilegeName)
      continue;

    return true;
  }

  return false;
}
于 2013-11-03T14:39:08.270 回答