Advertisement
Guest User

Untitled

a guest
Sep 18th, 2016
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. include "database.php";
  2. class User
  3. {
  4. private $userRoles = array();
  5. private static $db;
  6.  
  7. //Alternatively use your own way of setting your Database connection.
  8. public static function setDatabase($db)
  9. {
  10. global $db;
  11. self::$db = $db;
  12. }
  13.  
  14. //Populate the user object when it's created
  15. public function __construct($user_id)
  16. {
  17. $getUser = $this->db->prepare("SELECT * FROM admin WHERE id = :userid ");
  18. $getUser->execute(array(":userid" => $userid));
  19. if($getUser->rowCount() == 1)
  20. {
  21. $userData = $getUser->fetch(PDO::FETCH_ASSOC);
  22. $this->user_id = $user_id;
  23. $this->fnamename = ucfirst($userData['fname']);
  24. $this->email = $userData['email'];
  25. //etc.. More data if needed
  26. self::loadRoles();//Initiate the userroles
  27. }
  28. }
  29.  
  30. //Fill the array with this user's roles, it's
  31. protected static function loadRoles()
  32. {
  33. $fetchRoles = $this->db->prepare("SELECT user_role.role_id, role.role_name FROM user_role JOIN role ON user_role.role_id = role.role_id WHERE user_role.user_id = :user_id");
  34. $fetchRoles->execute(array(":user_id" => $this->user_id));
  35.  
  36. //Populate the array
  37. while($row = $fetchRoles->fetch(PDO::FETCH_ASSOC))
  38. {
  39. $this->userRoles[$row["role_name"]] = Role::getRolePermissions($row["role_id"]);
  40. }
  41. }
  42.  
  43. //Check if the user has a certain permission
  44. public function hasPermission($permission)
  45. {
  46. //If the user has more roles, check them too
  47. foreach ($this->userRoles as $role)
  48. {
  49. //Do the actual checking
  50. if ($role->hasPermission($permission))
  51. {
  52. return true;
  53. }
  54. }
  55. return false;
  56. }
  57. }
  58. $userid = 1;
  59. $db = new Database($dbhost,$dbuser,$dbpass,$dbname);
  60. $test = new User(1);
  61.  
  62. class Database
  63. {
  64. private $database = 'dbname';
  65. private $dbhost = 'localhost';
  66. private $dbuser = 'usr';
  67. private $dbpass = 'pw';
  68.  
  69. public function __construct($dbhost,$dbuser,$dbpass,$dbname) {
  70. $this->database = $dbname;
  71. $this->dbhost = $dbhost;
  72. $this->dbuser = $dbuser;
  73. $this->dbpass = $dbpass;
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement