MVC Architecture in PHP
MVC stands for Model-View-Controller. It is a type of architecture for developing software, recently pretty popular in web applications development. In short, the three things are pretty simple. Model is what interacts with the database, it would be the backend class code for an object-oriented language like PHP. View is basically the user interface. Controller is the logic that operates everything in between.
MVC and PHP development
The Model
The MVC structure is meant for reasonably-sized applications, using object-oriented coding. The Model part, in a PHP app, would usually be a class (or multiple classes). Fairly often, the class is a representation of a table you store in the database — member variables are the data columns, and member methods are operations that can be done. As an example, you might have a User class, having variables such as username, password, email address, and other things. Some of its methods might be a new user creation function, a login function, an authentication function, and a logout function.
Later on, we will see how User objects will be used in the Controller part of your application. The Model, in essence, tells you what methods are available — what can you do to the data in the database. I thought I should just clarify (if it wasn’t clear already) — this should be all PHP code, just as what you should do in OO-programming even without MVC. There should be no HTML or any kinds of outputs (redirection, etc.) here. If doing an action means that a redirection is needed or some output is needed, pass it as an argument or a return value. (It’s fairly basic programming practices, but you’d be surprised how many web apps programmers didn’t graduate with a CS degree..)
Here’s an example of the Model part of your code. Of course, there will be many more classes in a real application. This is just the code is the simplest form, without a lot of the details.
class User
{
var $username;
var $password;
var $email;
function User($u, $p, $e) // constructor
{
$this->username = $u;
$this->password = $p;
$this->email = $e;
}
function create()
{
// creates user in the db
}
function login()
{
// checks against db, does login procedures
}
static function authenticate($u, $p)
{
// checks against db
}
function logout()
{
// does logout procedures
}
}
The View
The View, in the simplest words, is the user interface. However, it doesn’t mean it would be just straight HTML. Minimal PHP logic will need to be used in your application’s interface a lot of times. For example, if you were to have the main logged-in page say, “Hello, [username]!” You would certainly need some PHP code to handle that, right? That is all part of the View. Of course, all the CSS, Javascript would be part of this too.
It is important that whatever PHP code in here is only what needs to be used to display the interface correctly. No additional “action” code belongs to the View — that is the Controller’s job, which we’ll see next.
This was easy to understand, but for clarification’s sake, let’s see an example anyway. Of course, the following isn’t even valid XHTML 1.0 (it lacks a DOCTYPE, for instance), but this is just an example.
<?php
require_once('User.php');
// makes sure user isn't already logged in
if (User::authenticate($_COOKIE['username'], $_COOKIE['password']))
{
header(”Location:/main.php”);
exit();
}
?>
<html>
<head><title>Please login</title></head>
<body>
<h1>Login</h1>
<?
if ($_GET['error'] == 1)
{
echo ‘Login incorrect. Please try again.<br />’;
}
?>
<form action=”login_action.php” method=”post”>
User: <input type=”text” name=”username” /><br />
Pass: <input type=”password” name=”password” /><br />
<input type=”submit” value=”Login” />
</form>
</body>
</html>
The Controller
Sometimes it is confusing to understand what the Controller needs to do, if you weren’t working on an actual application and just reading a book/an article. It would seem like the Model and the View are all you need. So let’s go back to a concrete PHP example.
Now imagine you have a login page setup. The login HTML form has to submit to somewhere, right? (Even if you’re using AJAX) You don’t submit directly to the Model class file (say, User.php), because that file only contains the class code, and no actual procedural code is there, so it won’t do anything. You certainly don’t submit directly back to the View file (say, login.php), even if it ends with a .php extension! Because its job is only to display the interface.
This is what the Controller is. Your form will submit to a file, say, login_action.php. In this file, you create an instance of the User class, running whatever initialization you need, and calling the appropriate methods that need to be run (login).
Some developers fall into the temptation to display outputs from the Controller, because it’s convenient. Imagine, if you had a login form, how easy is it to just print “Login incorrect” directly from the Controller PHP code? (assuming you aren’t using AJAX, for this particular example) It is an option, and I will tell you that many scripts do just that. However, to truly utilize a MVC structure’s advantage, the Controller (like the Model) should not display any HTML outputs, but rather use redirection. You may use cookies/sessions, database storage, flat file caching, or query string to the View file to store the states of your application; and then you should always let the View take care of displaying outputs, using these stored states.
Now let’s see an example of a Controller code.
<?php
require_once('User.php');
// in reality, a lot more error checking needs to be done.
$currentuser = new User($_POST['username'], $_POST['password'], ”);
if ($currentuser->login())
{
// set cookies for login info
header(”Location:/main.php”);
exit();
}
else
{
header(”Location:/login.php?error=1″);
exit();
}
?>
Conclusion
Using the MVC structure, code becomes a lot easier to understand. For other developers to join in to understand your code, as well as for yourself in the future when you come back to it after a while. Development is also a lot easier because you know exactly where to look for what piece of code. If you were going to change some message displaying in the interface, you only need to go to the View. If your database structure sees a change, such as passwords now encrypting in a different way, you only need to change your Model. The MVC architecture is very powerful and makes your object-oriented web apps development a lot more efficient.