I’m trying to apply a simple MVC pattern to my current website without any frameworks. Since i havent really gotten into oop yet im still using procedural at the moment.
i have a simple login form (view)
<form action="controller/login.php" method="Post"> <input type="text" name="username" placeholder="Username" /> <input type="text" name="password" placeholder="Password" /> <input type="submit" value="Sign in" /> </form>
this form will submit to the controller for login form. Controller will now check if both fields have inputs and “cleanse” more or less the input
if(isset($_POST['username'])){ $username = $_POST['username']; $password = $_POST['password']; $username_escape = mysqli_real_escape_string($connect, $username); $password_escape = mysqli_real_escape_string($connect, $password); } header("../model/login.php");
this is a really simple check right now however i was now wondering should i include controller into model and redirect to model from controller or form submit it at first place and have controller included.
Model
include_once("../controller/login.php"); $query = mysqli_query($connect, "INSERT into DB_table (username, password) VALUES($username_escape, $password_escape)");
Advertisement
Answer
It’s good that you’re trying to separate your concerns, but MVC is a design pattern based on top of OOP principles.
OOP works with objects, and those objects are defined by a class, which is like a blueprint.
So in this example, you’d want everything to go through the controller, then depending on whether you want to save out, you’d want to call the model.
eg.
class LoginController { public function indexAction() { $username = $_POST['username']; $password = $_POST['password']; if(!is_null($username) AND !is_null($password)) { $user = new ServiceUser(); $credentialsAreValid = $user->checkCredentials($username, $password); if($credentialsAreValid) { header("Redirect: Somewhere"); } } require_once __DIR__."/../templates/login.php"; } } class User { public function checkCredentials($username, $password) { $dsn = "mysql:host=localhost;dbname=db"; $dbuser = "root"; $dbpass = "pass"; $db = new PDO($dsn, $dbuser, $dbpass); $sth = $db->prepare("SELECT * FROM user WHERE username = ? AND password = ?"); $sth->bindValue(1, $username); $sth->bindValue(2, $password); $sth->execute(); if(count($sth->fetchAll())>0) return true; return false; } }
As you can see the logic is separated into a service, and is only called if it is needed. We’ve also used PDO to prevent SQL injections, (though one shouldn’t really be creating objects in here).
I would suggest you look into autoloading, and have a play with a framework like Silex as it will teach you these principles.