I am quite new to the MVC concept. I already know how to program object-orientated from other languages like C++ or Java. I have implemented a little login system for test purpose. I am not sure if my implementation is the best way to follow MVC. Any feedback is welcome.
The class ControllerUser
is instantiated in a file called init.php
. The $controllerUser
variable is therefore accessible on every page. I am also not sure if this is the best way. Can somebody also explain to me when to use the view class and which functions should it have? I know that it should render/output the page and the data... does this mean that it should print the logout/login form?
This is my database class in which the connection is established. All models will inherit from this class.
class.database.php
class Database {
protected $pdo;
public function connect() {
$datahost = 'localhost';
$datauser = 'root';
$datapass = 'PASSWORD';
$database = 'DATABASE';
try {
$options = [ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ];
$this->pdo = new PDO('mysql:host='.$datahost.';dbname='.$database.'', $datauser, $datapass, $options);
} catch (PDOException $e) {
print "Mysql Connection failed: " . $e->getMessage();
die();
}
}
public function disconnect() {
$this->pdo = NULL;
}
}
Everything will have an own model, controller and view, when necessary. In this case it is the user.
User controller:
controller.user.php
<?php
class ControllerUser {
private $model;
function __construct($datatable) {
$this->model = new ModelUser($datatable);
}
public function login($email, $password) {
$user = $this->model->getByEmail($email);
if($user && password_verify($password,$user['password'])) {
if($user['status']==1) {
if($user['verified']==1) {
$_SESSION['id'] = $user['id'];
$this->model->updateIP($user['id']);
return true;
}
else {
throw new Exception('Not verified!');
}
}
else {
throw new Exception('Your account is locked. Contact a staff member.');
}
}
else {
throw new Exception('Email or password wrong!');
}
}
public function logout() {
if($this->isLoggedIn()) {
session_destroy();
unset($_SESSION['id']);
return true;
}
}
public function isLoggedIn() {
if(isset($_SESSION['id'])) {
$status = $this->model->getById($_SESSION['id'])['status'];
if($status==1) {
return true;
}
else {
throw new Exception('Your account is locked. Contact a staff member.');
}
}
}
}
?>
User model:
model.user.php
<?php
class ModelUser extends Database {
private $datatable;
function __construct($datatable) {
$this->connect();
$this->datatable = $datatable;
}
public function getByEmail($email) {
$stmt = $this->pdo->prepare("SELECT * FROM ". $this->datatable ." WHERE email = :email");
$result = $stmt->execute(['email' => $email]);
return $stmt->fetch();
}
public function getById($id) {
$stmt = $this->pdo->prepare("SELECT * FROM ". $this->datatable ." WHERE id = :id");
$result = $stmt->execute(['id' => $id]);
return $stmt->fetch();
}
public function updateIP($id) {
$statement = $this->pdo->prepare("UPDATE ". $this->datatable ." SET ip = :ip WHERE id = :id");
return $statement->execute(['ip' => $_SERVER['REMOTE_ADDR'], 'id' => $id]);
}
function __destruct() {
$this->disconnect();
}
}
?>
User view... I am not sure what could be inside of view...
The function there is only for test purpose:
view.user.php
<?php
class ViewUser {
public function printUserInformation($data) {
foreach($data as $key => $value){
echo $key.': '.$value.'<br>';
}
}
}
?>
Everything comes to use on the login page:
login.php
<?php
if(isset($_GET['login'])) {
$viewUser = new ViewUser(); //test
$modelUser = new ModelUser("users"); //test
try {
$controllerUser->login($_POST['email'], $_POST['password']);
$viewUser->printUserInformation($modelUser->getById($_SESSION['id'])); //just a test
}
catch(Exception $e) {
echo $e->getMessage();
}
}
if(isset($_GET['logout'])) {
$controllerUser->logout();
}
if(!$controllerUser->isLoggedIn()) {
?>
<form class="login-form" action="?login=1" method="post">
<input type="email" size="40" maxlength="250" name="email" placeholder="Email address" required>
<input type="password" size="40" maxlength="250" name="password" placeholder="Password" required>
<button type="submit" value="Login" class="button style1">login</button>
<input type="checkbox" id="stayloggedin" name="stay_loggedin"><label for="stay_loggedin" >stay logged in</label>
</form>
<?php }
else {
?>
<form class="logout" action="?logout=1" method="POST" style="display: inline-block;">
<button type="submit" name="logout">logout</button>
</form>
<?php }
?>