Model View Controller(MVC) in PHP

The model view controller pattern is the most used pattern for today’s world web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there are more than a dozen PHP web frameworks based on MVC pattern.

Despite the fact that the MVC pattern is very popular in PHP, is hard to find a proper tutorial accompanied by a simple source code example. That is the purpose of this tutorial.

    The MVC pattern separates an application in 3 modules: Model, View and Controller:

  • The model is responsible to manage the data; it stores and retrieves entities used by an application, usually from a database, and contains the logic implemented by the application.
  • The view (presentation) is responsible to display the data provided by the model in a specific format. It has a similar usage with the template modules present in some popular web applications, like wordpress, joomla, …
  • The controller handles the model and view layers to work together. The controller receives a request from the client, invokes the model to perform the requested operations and sends the data to the View. The view formats the data to be presented to the user, in a web application as an html output.

The above figure contains the MVC Collaboration Diagram, where the links and dependencies between figures can be observed:
mvc-collaboration

Our short php example has a simple structure, putting each MVC module in one folder:
mvc-structure

Controller

The controller is the first thing which takes a request, parses it, initializes and invoke the model and takes the model response and sends it to the presentation layer. It’s practically the liant between the Model and the View, a small framework where Model and View are plugged in. In our naive php implementation the controller is implemented by only one class, named unexpectedly controller. The application entry point will be index.php. The index php file will delegate all the requests to the controller:

	// index.php file
	include_once("controller/Controller.php");

	$controller = new Controller();
	$controller->invoke();

Our Controller class has only one function and the constructor. The constructor instantiates a model class and when a request is done, the controller decides which data is required from the model. Then it calls the model class to retrieve the data. After that it calls the corresponding passing the data coming from the model. The code is extremely simple. Note that the controller does not know anything about the database or about how the page is generated.

include_once("model/Model.php");

class Controller {
     public $model;	

     public function __construct()  
     {  
          $this->model = new Model();
     } 
	
     public function invoke()
     {
          if (!isset($_GET['book']))
          {
               // no special book is requested, we'll show a list of all available books
               $books = $this->model->getBookList();
               include 'view/booklist.php';
          }
          else
          {
               // show the requested book
               $book = $this->model->getBook($_GET['book']);
               include 'view/viewbook.php';
          }
     }
}

In the following MVC Sequence Diagram you can observe the flow during a http request:
mvc-sequence1

Model and Entity Classes

    The Model represents the data and the logic of an application, what many calls business logic. Usually, it’s responsible for:

  • storing, deleting, updating the application data. Generally it includes the database operations, but implementing the same operations invoking external web services or APIs is not an unusual at all.
  • encapsulating the application logic. This is the layer that should implement all the logic of the application. The most common mistakes are to implement application logic operations inside the controller or the view(presentation) layer.

In our example the model is represented by 2 classes: the “Model” class and a “Book” class. The model doesn’t need any other presentation. The “Book” class is an entity class. This class should be exposed to the View layer and represents the format exported by the Model view. In a good implementation of the MVC pattern only entity classes should be exposed by the model and they should not encapsulate any business logic. Their solely purpose is to keep data. Depending on implementation Entity objects can be replaced by xml or json chunk of data. In the above snippet you can notice how Model is returning a specific book, or a list of all available books:

include_once("model/Book.php");

class Model {
	public function getBookList()
	{
		// here goes some hardcoded values to simulate the database
		return array(
			"Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),
			"Moonwalker" => new Book("Moonwalker", "J. Walker", ""),
			"PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")
		);
	}
	
	public function getBook($title)
	{
		// we use the previous function to get all the books and then we return the requested one.
		// in a real life scenario this will be done through a db select command
		$allBooks = $this->getBookList();
		return $allBooks[$title];
	}
	
	
}

In our example the model layer includes the Book class. In a real scenario, the model will include all the entities and the classes to persist data into the database, and the classes encapsulating the business logic.

class Book {
	public $title;
	public $author;
	public $description;
	
	public function __construct($title, $author, $description)  
    {  
        $this->title = $title;
	    $this->author = $author;
	    $this->description = $description;
    } 
}

View (Presentation)

The view(presentation layer)is responsible for formating the data received from the model in a form accessible to the user. The data can come in different formats from the model: simple objects( sometimes called Value Objects), xml structures, json, …

The view should not be confused to the template mechanism sometimes they work in the same manner and address similar issues. Both will reduce the dependency of the presentation layer of from rest of the system and separates the presentation elements(html) from the code. The controller delegates the data from the model to a specific view element, usually associated to the main entity in the model. For example the operation “display account” will be associated to a “display account” view. The view layer can use a template system to render the html pages. The template mechanism can reuse specific parts of the page: header, menus, footer, lists and tables, …. Speaking in the context of the MVC pattern

In our example the view contains only 2 files one for displaying one book and the other one for displaying a list of books.

viewbook.php

<html>
<head></head>

<body>

	<?php 

		echo 'Title:' . $book->title . '<br/>';
		echo 'Author:' . $book->author . '<br/>';
		echo 'Description:' . $book->description . '<br/>';

	?>

</body>
</html>

booklist.php

<html>
<head></head>

<body>

	<table>
		<tbody><tr><td>Title</td><td>Author</td><td>Description</td></tr></tbody>
		<?php 

			foreach ($books as $title => $book)
			{
				echo '<tr><td><a href="index.php?book='.$book->title.'">'.$book->title.'</a></td><td>'.$book->author.'</td><td>'.$book->description.'</td></tr>';
			}

		?>
	</table>

</body>
</html>

The above example is a simplified implementation in PHP. Most of the PHP web frameworks based on MVC have similar implementations, in a much better shape. However, the possibility of MVC pattern are endless. For example different layers can be implemented in different languages or distributed on different machines. AJAX applications can implements the View layer directly in Javascript in the browser, invoking JSON services. The controller can be partially implemented on client, partially on server…

    This post should not be ended before enumerating the advantages of Model View Controller pattern:

  • the Model and View are separated, making the application more flexible.
  • the Model and view can be changed separately, or replaced. For example a web application can be transformed in a smart client application just by writing a new View module, or an application can use web services in the backend instead of a database, just replacing the model module.
  • each module can be tested and debugged separately.

The files are available for download as a zip from http://sourceforge.net/projects/mvc-php/files/mvc.zip/download

Did you enjoy this tutorial? Be sure to subscribe to the our RSS feed not to miss our new tutorials!
... or make it popular on

144 Comments

  1. Thank you very much for this tutorial. I was searching for a good, clean, small tutorial for over 2 days now. This is the only one I understand, and I really learned how it works now!

    Thank you very much. I will recommend this page / tutorial for everyone who wants to learn MVC.

  2. Several years later, and there are always beginners who don’t have time to read books about PHP and MVC. Thanks for the article.

  3. Great tutorial thanks, finding info on MVC in PHP is difficult, I am seeing allot of MVC PHP books being published recently which is nice. I am surprised MVC is not more widely implemented using PHP considering it is really was the first main stream web development language.

  4. Quite old post but still applies to our “modern days”.
    It’s really straightforward!!! Very nice article.

    Well, just to add my contribution, as I have read a lot of posts about MVC, I got a little bit confused when I saw the first picture in this post. Don’t you think it has more todo with the MVP (Model View Presenter) pattern instead of MVC ?

    I’m asking it because as far as I know, in ***MVC*** the view talks to the model without having to go through Controller.

    Anyways, I believe MVP is just another flavor of MVC and no matter whether I’m correct or wrong your post is still very useful.

    Cheers!

  5. very well written article about MVC basics. Now I can say I know how to work in MVC pattern. I started playing with your code using my oop knowledge for example I changed the code of main index.php file to

    function __autoload($class_name)
    {
    include_once ‘controller/’ . $class_name . ‘.php';
    }

    $controller = new Controller();
    $controller->invoke();

  6. Excellent Tutorial I had ever taste. M.V.C. is not a stranger any more. It’s great to receive such guidance. I am really very thankful to the author(s).

  7. Thanks for the tutorial. Honestly, it is a little hard to read because of the grammar. (It is interesting to me that someone with such an affinity for computer language doesn’t think subject/verb relationships are important).
    Example: ‘The controller is the first thing which takes[proper] a request, parse[S] it, initialize[S] and invoke[S] the model and takes[proper] the model response and send[S] it to the presentation layer’.
    It just made me have to read it a couple of times before I got the meaning. There was a lot of that. You got it correctly the first time: “takes”, but the other verbs are made unclear in their tense by not adding the “s” (is it future or future imperative? No, it’s present tense: “Takes” or “is taking”. Again, not trying to smart-off, just thought you should know.

  8. I have to say that this is a very cool tutorial..
    I’ll also like to add that mvc is much more easier to implement in oop (Object Oriented Programming). I don’t know about mvc in aspect oriented approach for php.

  9. Thank you, a very complete and comprehensive tutorial about MVC with great example. This help me a lot about understanding MVC

  10. Thank you so much. I’ve been hard coding PHP for a long time now but never wanted to give frameworks or concepts a try. Recently, I tried getting into Zend Framework 2 and the MVC concept (which I’m familiar with) became a blur. I understood it but wasn’t sure how to use it in practice. You gave me a clear understanding of it and now I can proceed to learn further and enhance my applications.

    Cheers.

  11. Just wanted to send you a big THANKS also in december 2012, just to show that this post is still very much being appreciated :)

  12. Can you update the article and show the add, update, and delete functions ?
    Show how you would add,etc. to the array.
    Your article is clear and simple.

    Thank you.

  13. I fixed some of the grammar mistakes. I happens a lot since English is not my native language, but I try to improve it. Thanks for pointing it out.

  14. A great tutorial that’s seen the test of time and still relevant today, I have read thousands of online tutorials in my time, and the style of this one would be the best I have seen. I also write Tutorials for a university in a similar style for students trying to comprehend complex programming concepts.
    Sure there are minor technical things that could be improved on in your tutorial(but I understand for simplicity why you did it that way), but you have an excellent way of making the complex, simple. It would be nice to see this as a series of articles in a similar simple style covering how SQL is populated into models and eventually evolving to the concept of HMVC.
    By the way I have always used a separate model to the data model as you do but I call my model class the plural of the data class as in “Books”, it handles all the SQL and multiple book objects and can and return an array of book objects to pass around the application. The naming convention plural of data object makes it easier to follow code.
    I would like to publish my work to the WWW for the benefit of others but its copyright is owned by he university that I work for. Maybe in retirement…. I could continue my passion online.

  15. I got this web site from my friend who shared with me regarding this web page
    and at the moment this time I am browsing this website and reading very informative posts here.

  16. Dear Admin,

    I really appreciate your article for ever simplest way to know basic meaning of MVC and wayout to start with it and get knowledge to learn complex frameworks.

    I have one query, you explained very well how we can fetch Data from Model and display it on View but I will be grateful to you if you please explain extended version of this Article with any User input For, which will be going to save into the Database.

    I am PHP programmer , I know how to create this in Normal Core PHP project but I am wondering if you could help me to start with it.

    I trust, you will respond my query at earliest.

    Cheers!
    Blossom

Leave a Comment.