MVC architecture in PHP development

19 Jan

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, Ruby on Rails, or C++. View is basically the user interface. Controller is the logic that operates everything in between.

They are easy to explain, but sometimes the concept is a little abstract and it’s hard to grasp for someone who doesn’t know what MVC is to begin with. To be honest, all my years in web development I never really understood exactly what MVC is, until recently when I started doing development in Ruby on Rails. In this article, I hope to explain MVC architecture development in PHP terms, so the average web apps programmer may benefit from understanding this powerful architecture.

MVC and PHP development

The reason I mentioned Ruby on Rails is because you really have to understand how to develop an application with the MVC architecture to do anything at all on RoR. (Next time, I will write another article on RoR — but this time, I’ll talk about PHP development.)

The Model-View-Controller separation actually makes a lot of sense, it is actually natural for a developer to divide his/her code that way when working on a reasonably large application. Java has classes, JSP and struts; Ruby on Rails has a built-in MVC structure; but even when PHP doesn’t have anything like that, it doesn’t mean you can’t do it.

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'] )
{
   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.

About these ads

9 Responses to “MVC architecture in PHP development”

  1. ^^ December 30, 2010 at 5:03 am #

    tnx for the information..coz.before i totally doubt the flow of mvc and how they interact each other….and now i know!!!…..

  2. Mahesh March 31, 2011 at 1:10 pm #

    Super Duper. Good work. Very Simple and damn informative. Thanx man

  3. ajay May 16, 2011 at 7:48 pm #

    really a good explanantion.Love to see it.

  4. AJIL .K.MOHANAN (@ajilkmohanan) October 31, 2011 at 3:27 am #

    good one …but i need another simple example for using MVC in php…pls..if u dont mnd…

  5. Mudasir November 12, 2011 at 11:17 am #

    Nice post for begginers and to get good idea. Thanks

  6. Shamizai April 4, 2012 at 11:07 am #

    So nice, very helpfull.

  7. Cam April 18, 2012 at 1:21 am #

    Hey man, thank you so much!!! I got more out of this one page explanation then 4h+ googling and ready 10s of pages about MVC.

    Many thanks!

  8. Rohit April 24, 2012 at 1:14 pm #

    Good !

  9. Aman May 31, 2012 at 8:58 am #

    very useful…
    thanx for this example…..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: