I'm making a very basic user system, and this is what I have so far:
<?php
/* The class for constructing any user's information
*/
class User {
protected $userId, $email, $userGroup;
protected function getEmail() {
return $this->email;
}
protected function getUserId() {
return $this->userId;
}
public function __construct($userId, $email, $emailGroup) {
$this->userId = $userId;
$this->email = $email;
$this->userGroup = $emailGroup;
}
// Method for checking whether user can view a specific page
public function canViewPage($pageId) {
$userGroup = new UserGroup($this->userGroup);
if($userGroup->canViewPage($pageId)) {
return true;
}else{
return false;
}
}
// Method for checking permissions
public function hasPermissions($alias) {
/* alias is the name of the permissions. ie can-book
* create usergroup object based on current user's usergroup */
$userGroup = new UserGroup($this->userGroup);
if($userGroup->hasPermissions($alias)) {
return true;
}else{
return false;
}
}
}
class UserMapper {
// database connection
private $db;
public function __construct($db)
{
$this->db = $db;
}
public function findByUserId ($userId) {
$userObject = new User();
$q = $this->db->prepare("SELECT userId, email, userGroup FROM user WHERE userId = :userId");
$q->bindValue(":userId", $id);
$q->setFetchMode( PDO::FETCH_INTO, $userObject);
$q->execute();
$q->fetch(PDO::FETCH_INTO);
return $userObject;
}
}
?>
Then on my main script, I include the user.class.php
(as shown above) and do this:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT => true));
$getUser = new UserMapper($dbh);
$user = $getUser->findByUserId(41);
echo $user->getEmail();
?>
Is this all correct? Or have I misunderstood? Is there a way of simplifying this? I've tried to keep the code as simple as possible. Am I correct for having getters (getEmail
, etc.) as well as methods such as canViewPage
, within the user class?
Also, should it be:
$userGroup = new UserGroup($this->userGroup);
or should I do something like this again?
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT => true));
$getUserGroup = new UserGroupMapper($dbh);
$userGroup = $getUserGroupMapper->findByUserId($this->userGroup);
Is there a simpler way?