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?
Create a new class AdminPrivilege:
class AdminPrivilege extends base {
protected $id;
protected $admin_id;
protected $privlege;
protected $allowed;
public function setter() { }
public function getter() { }
/* ETC */
}
Then in your controller class make a method called loadAdminPrivilegesByAdminID($adminID). In this method load the privileges for the admin create the AdminPrivilege objects and return them as array and attach the array to your admin object.
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 */
}
To check if an admin has a specific privlige is easy. In your controller class make a new method checkPrivilege($adminObj, $privilegeName):
public function checkPrivilege($adminObj, $privilegeName) {
foreach($adminObj->getPrivileges() as $prv) {
if($prv->privilege != $privilegeName)
continue;
return true;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With