PHP HTML CSS Tutorials

Tutorials, Resources and Snippets

Model View Controller(MVC) in PHP

144 comments

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

Written by admin

August 10th, 2009 at 12:38 am

Posted in Patterns

Tagged with , ,

144 Responses to 'Model View Controller(MVC) in PHP'

Subscribe to comments with RSS or TrackBack to 'Model View Controller(MVC) in PHP'.

  1. I might be being a little picky here. I admit, I’m not a PHP guy I’m a Java, C# guy. But the Model is the data, not necessarily the mechanism for retrieving the data. In the Java world we have Business Logic and Persistence layers that handle those functions. And the Model is just a representation of data used by a view.

    Of course this might be different in the PHP world.

    Tom Quaile

    12 Aug 09 at 2:36 pm

  2. This is a big and exhaustive discussion but I dream that one day people will stop calling PHP developers script kiddies so here’s my attempt:

    Model should take care of business logic, NOT only datam while the Controller should take care of the app logic.

    In your example, the model should have a function getBookByTitle() which is used by the Controller.

    I’ll write about MVC in PHP when I have the time to do it. Any way thank you for your attempt. It certainly help people. Still, be careful with what you write.

    The great majority of the articles about MVC I read on the internet have wrong informations in them.

    Read more at http://www.littlehart.net/atthekeyboard/2007/04/27/fat-models-skinny-controllers/

    Bruno Cassol

    12 Aug 09 at 2:48 pm

  3. Nice little primer here, thanks for this, i’ve been looking for something like this that skims the surface – i’m finding that most of the tutorials on the web are too technical. You’ve broken it down quite nicely.
    Thanks again!

    Michael Caputo

    13 Aug 09 at 6:48 am

  4. @Tom Qualile, I agree in Java and other languages there are specialized layers for Persistence. This example is a simple one just to explain the MVC pattern. After all in a MVC architecture the Persitance layer is just a part of the Model.

    @Bruno Cassol: the model already includes “public function getBook($title)”

    admin

    15 Aug 09 at 2:03 pm

  5. What is the difference between business logic and app logic? Im really new to php architecture and am learning the ropes of php. Im Trying to learn more about PHP, OOP in general. I want to do web application development.

    MVC patterns are a little fuzzy to me though.

    Paul

    19 Aug 09 at 5:25 am

  6. Maby it’s handy to add the source attatched to your site, so ppl can try your example without copying and pasting the content.

    Bruggema

    1 Nov 09 at 1:51 am

  7. Bussines logic is usualy located in in the model layer. In most of the cases it defines the operations that can be done in the “backstage”: Examples of business rules:
    - A library can store only 1000 books.
    - Each book should have at least one author.
    - Each time a book is returned the application should send a mail to the librarian.

    The app logic is located usually in the controller area. It is more related with the operations visible to the user. For example the application logic defines which objects in the model layer should be used for a specific request and what layout should be displayed. Application logic can also define the order in which the screens are displayed.

    In practice the border between application logic and business logic is not always very visible.

    admin

    4 Nov 09 at 7:46 am

  8. Thans @Bruggema, the files are available for download at http://sourceforge.net/projects/mvc-php/files/mvc.zip/download

    admin

    4 Nov 09 at 11:23 am

  9. This was exactly what I was looking for. A simple explanation on the MVC model with a simple example to go with it.

    Thanks a bunch!

    Rick

    13 Jan 10 at 10:43 am

  10. Well this is the first time I completed an MVC tutorial and understand it. Thanks.

    Chris

    8 Mar 10 at 2:43 pm

  11. Great tutorial! Finally a tutorial, with actual working code! A great started to start with MVC in PHP.

    Bryan

    12 Apr 10 at 10:01 am

  12. Thanks for the high level overview, it’s what I was looking for.

    Jeff H

    17 Apr 10 at 1:07 pm

  13. excelent tutorial, thanks.

    berthely

    13 May 10 at 6:34 am

  14. I have learned a lot on this example. Thank you for posting this tutorial.

    Edsel

    26 May 10 at 6:27 am

  15. This is a good tut. I am new to this. I have been searching for something like this but they are all too complicated. I could more or less grasp yours.
    I am asking you in regard to Model.php file. How do you actually populate it with records existing from a database? And that it could be retrieved through the $title.
    If you could find the time, I really would appreciate this extra learning.

    Thanks a million!

    Nicky

    2 Jun 10 at 3:13 am

  16. this is the best MVC tutorial I came across so far. thanks for sharing!

    I am new to MVC and I am still confused with the class Model and the class book in your example…

    for instance, I have my website and the content of my webiste is pulled from a database… so when I request a specific page for instance, http://www.mysite.com/index.php?pg=profile or with clean url http://www.mysite.com/profile

    so usually, I will get the content from the SQL query,

    $sql = ”
    SELECT * FROM root_pages
    WHERE root_pages.pg_url = ‘”.$_REQUEST['pg'].”‘
    “;

    so then should this $sql be put in the class book or class model??

    I have a directory folder which keeps all my CMS files, which contains update, insert, delete SQL queries, html forms, and pages that display the db items into lists, etc.

    so if I implement MVC on my website, then I am going to relocate these CMS files into different locations, like some in the model folder, and some in view folder and others in controller folders, is it correct??

    Lau

    3 Jun 10 at 10:20 am

  17. @Lau

    1. From the MVC perspective it doesn’t really matter where the SQL code should be put. In this example there is a model class to demonstrate the MVC pattern. The main purpose of the model class is to provide a central point for all the operations exposed by the model. The book class will be used in the view layer so it should be a simple data object. A good practice would be to create a separate class that will handle the book db operations(a DAO layer inside the Model).

    2. A pattern does not force you to use a standard folder structure. I personally think that it is better to split the files in separate folders. The 3 layers (M-V-C) should be as decoupled as possible. When you write your code try to imagine that you have to use the Model or the Presentation layer in another application. If you could achieve it by simply coping its directory then you have a good class design. If you have to change lots of files it means the classes are coupled(bad design).

    admin

    8 Jun 10 at 3:13 pm

  18. Just what I was looking for, a simple tutorial that clearly explains how MVC works with PHP at it’s simplest level.

    Lee

    18 Jun 10 at 2:26 am

  19. A nicely written tutorial. I now understand the MVC model. However, one thing is not clear: in your reply to Lau.
    “The book class will be used in the view layer so it should be a simple data object”.
    So what is implied by “book class used in the view layer”. How and why is model class used in View. Also stated in your article

    “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”.

    This is not clear as how and why Entity class is exposed to View Layer

    Admin: The entity should be exposed because the data require a structure. The view and the model need to speak a “common language”. That is represented by the entity classes.

    Amit

    4 Jul 10 at 6:09 am

  20. Hi,
    thanks a for a step by step tutorial with examples broken into great depth.
    I tried going through some of the MVC tutorials,they just went above my head without any learning.thanks a lot again.


    rgds

    sameer

    5 Jul 10 at 1:25 am

  21. First Thanks for a very informative Tutorial. I’m almost there ;-) .

    You mentioned above :

    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.

    Does this mean that each function that is being required from the Controller has to be implemented in one Model. E.g:

    include_once(“model/Book.php”);
    include_once(“model/Teacher.php”);
    include_once(“model/Students.php”);

    class Model {
    public function getBookList(){}
    public function getBook($title){}

    public function getTeacher($name){}
    public function getStudent($name){}

    }

    Thanks in advance for the Answer.

    Admin: Yes, that’s true.

    Furqan

    11 Aug 10 at 11:26 pm

  22. Probably the best article/tutorial on MVC. Simple, concise and the example works on first run. Thanks!

    jstorm

    9 Sep 10 at 7:34 pm

  23. simple, yet very informative, well done!

    ivan

    17 Sep 10 at 8:04 am

  24. This is very good tutorials for beginner….

    Rakesh Singh

    27 Sep 10 at 1:17 am

  25. Nice tutorial. Is there anyone know how to implement MySQL database and CRUD in this Model class? I tried to experiment it in this model class but it looks like unfortunate. Do PHP activerecord and PERL handle this? Some reviews said both probably handle them within your concept than own one.

    Ivan

    13 Oct 10 at 4:45 am

  26. Wow. Great Tutorial! Very clear and helpful.

    Thanks.

    Michael

    23 Oct 10 at 10:26 pm

  27. MVC pattern was displayed very easy format. Using this tutorial , new guys easy OOPs PHP very quickly.

    rajesh

    26 Oct 10 at 6:13 am

  28. 1. Plz , tell me how to genarate getBookList() in model/Model.php using database?
    2. Plz , tell me how to genarate getBook($title) in model/Model.php using database?
    3. Then i want add one book , how can i create form?
    4. I want Add/Edit/delete functionalities for the book. So plz reply soon.

    If you reply very earlier , it will be very useful for me.

    rajesh

    26 Oct 10 at 6:19 am

  29. Dude, thanks for this small article. This is exactly what I was looking for: a simple tutorial with PHP code and not framework-specific. Thanks for taking the time to share.

    Regards,
    MV

    Mvaldez

    5 Nov 10 at 11:24 am

  30. I have always been confused with how MVC works with php and even more confused when looking at others tutorials on the web (There’s quite a lot out there) but it’s the first time I’m getting a clear understanding about MVC with this tutorial. The best I came across on the web. Thanks a lot for sharing this. May God bless you.

    dadamoto

    11 Nov 10 at 7:22 am

  31. Guys, before asking how to do more with this example, please keep in mind that it is just an example simplified at maximum to ease the understanding of MVC pattern. This is the one and only purpose. So, I would recommend not to rely on it for real projects especially if you don’t know how to query the db in php or how to create forms.

    admin

    18 Nov 10 at 9:45 am

  32. Thank you very much to the author for writing such a useful article. Now I get more familiar with the MVC. However, I still got a question, hoping someone can explain.

    Refering to Furqan’s example of including the book, teacher, student into the Model, won’t it be too clumsy for such a big Model class? Say, now I just need to get a book into the book model, it’s useless to include teacher and students (and potentially more classes in the future). Why not split it into smaller ones that’s specific to the related classes? As later on, I may write other book retrieval methods like by author, ISBN etc. It’ll be hard to maintain such a big Model with all unrelated methods scrambled together.

    I would expect a book specific model class, that queries the DB, and return the required books I want. Then have it put in the Book class and returned to the corresponding View. This way, we can have a manageable Model class while still able to pass the simple data object around.

    I’m not sure my idea is correct, but let’s share and discuss :)

    Joe

    22 Nov 10 at 12:53 am

  33. Awesome!!! The best example I found! Easy to understand and follow. Thanks!

    anthony

    22 Nov 10 at 2:40 am

  34. Thank you for this clear, concise, simple overview. It is exactly what I was looking for. I’ve been coding PHP for about 13 yrs. I use Objects and Classes and DALs but I’ve never really grokked MVC, no matter how many other articles I’ve read. This hit it home with the exact level of abstraction I needed to start writing with MVC in mind (as opposed to just blindly bashing at code and using a hammer to make it fit into the file structure.)

    Sean Prunka

    23 Nov 10 at 10:23 am

  35. Very good tutorial, thanks.

    JackAndK

    23 Nov 10 at 7:36 pm

  36. Although i still don’t beging with mvc, i’m searching the web for good tutorials to start and i believe than this is a very good tutorial.

    Sorry, my english is bad.

    From Colombia.

    De la Cuesta

    24 Nov 10 at 2:31 pm

  37. Thanks for such a helpful article. Having used some object oriented code written by others, and hacking stuff together in the Palm development environment, I can get things to run, but until now have really had trouble seeing the logic behind the structure, and having this example was clutch. Thanks a million!

    devT

    8 Dec 10 at 7:54 am

  38. Hi I liked your article a lot . But I have a ques..
    bookList.php and viewBook.php are the files in the view folder and they come under the presentation part
    which is supposed to be just the html code. Is there a way I can remove this php code from the html file. I dont want to put php code in my html files. So if you have any solution to this . Please do reply me.
    Thanks

    Aks

    6 Jan 11 at 8:21 am

  39. Nice tutorial. Would be better if filenames preceded every code snippet. You’ve done this on a few of them but some have been missed.

    Gammerz

    12 Jan 11 at 9:46 am

  40. How can i create the Database and request in MVC? I have tried it but it’s difficult than non-MVC. Has anyone experienced it and simplified the example?

    Ivan

    16 Jan 11 at 3:49 pm

  41. Hi, I’m new to this MVC style coding and kind of just thrown in the deep end on programming in this framework and was wondering about a few things…

    So in the “Model.php” page on line 8 where the array of books start, how would you use a database connection in here?

    **************************************************************
    mysql_connect(“localhost”,”username”,”password”);
    mysql_select_db(“dbname”);

    and after a connection, where would you place something like this:

    $sql = mysql_query(“select tableName1, tableName2, tableName3 from table”);
    while ($row = mysql_fetch_array($sql)) {
    $title = “$row[1]“;
    }

    Thx,
    RT

    RT

    26 Jan 11 at 11:24 am

  42. Thanks a lot …for ‘very informative tutorial’

    Iwan

    27 Jan 11 at 4:46 pm

  43. Great tutorial! Thank you very much. Although I do not speak english very well I understand whole tutorial. thank you.

    Darkry

    29 Jan 11 at 2:27 am

  44. Great overview, I really like the diagrams.
    I am playing catchup in going from procedural programming to OO and Web development, so this really helps.

    Jennifer

    30 Jan 11 at 6:37 am

  45. That would be ok for a start…

    admin

    19 Feb 11 at 4:22 am

  46. Hello,

    I’m kinda new to MVC and this tutorial was so helpful for me. I was just wondering is there any way to make these urls more SEO friendly. ( using the .htaccess file )

    Eg : http://localhost/mvc/index.php?book=PHP for Dummies to http://localhost/mvc/book/PHP for Dummies

    Any advice given would be greatly appreciated.

    Cheers
    Mahesh

    Mahesh

    21 Feb 11 at 1:09 am

  47. One of the cleanest implementations of MVC I have ever seen.

    Would be nice to follow this post up with a few ammendments and additions, i.e. a Registry class for storing all your PHP constants etc… and some really basic database setup stuff.

    Really useful post.

  48. For over 10 years, I have used an object for my database calls, happy that if I switched to postGres, etc., I would only have to use a new global.inc file and change my queries.

    I also have refined a custom funcs.inc file with my teams that is useful across various applications with a few mods for each. The php web pages serve as the view/model for me just fine, and any common calls are made into functions or more includes to build arrays to show in the view.

    I have yet to run into a downside with this approach, except in how it may be less conducive to team programming. The logic is very clean and less code loads up in each apache request.

    What am I missing?

    Drew Deal

    1 Apr 11 at 3:18 pm

  49. HELLO

    Nice tutorial ONE OF THE BEST ON THE WEB … and it works

    bye !

    jc

    5 Apr 11 at 11:11 pm

  50. Thank u for posting.

    söve

    12 Apr 11 at 11:39 pm

  51. Excellent tutorial!!!
    I would love to see more about MVC.

    AbAdDoN

    18 Apr 11 at 4:21 pm

  52. Great tutorial!
    I’m kindda new to mvc and oo, I really enjoy learning new stuff.
    I would like to make a login(DB) page and add,edit new records (CRUD) based on this tutorial, does any one wants to give me a hand? I’m working on CRUD right now,
    so if you’re interested in continuing this tutorial, please post here or email me at meegloz at myopera dot com.
    Maybe we can post the final work here, :)

    Thanks!

    marc

    30 Apr 11 at 4:37 pm

  53. This is a great tutorial. I have to disagree with “admin” that you should not jump into MVC using what you learned in this tutorial. Granted yes, you still need more, like an understanding of database interaction, but I think it is a much better stepping stone to try to make some basic projects with a self-created basic MVC framework rather than overwhelming yourself with a more professional framework that may even be overkill for what you need.

    Matt

    11 May 11 at 11:34 am

  54. Thank you so much for the excellent tutorial.

    I’ve been designing a site while using your tutorial as a reference, and I’ve hit a gray area with respect to the relationships among the components when lets say the view contains an html form that uses POST. Should the action attribute be set to the controller or index.php?

    Also, assuming you POST directly to the controller, if there’s a cycle where the controller includes the view and the view POSTS to the controller, how can one keep the relative paths in order.

    Sajjad

    16 May 11 at 5:11 pm

  55. This is a really cool example of how MVC works, thank you thank you thank you :)

    Nordin

    19 May 11 at 4:27 am

  56. its really nice..easily can understand..thanks

    Ganesh kumar

    19 May 11 at 6:33 am

  57. Excellent tutorial.I have already learned html.But I didn’t clear idea.Your blog tutorial is so easy to practice and learn.Thanks for adding this in your blog.

  58. Thanks a lot mate :)

    Could you please write more articles about the MVC pattern please.

    Thanks again

    mesaber

    9 Jun 11 at 7:47 pm

  59. VERY NICE TUTORIAL

    Mahendra

    21 Jun 11 at 3:41 am

  60. Hello,

    Thank you very much for such a lovely example but m able to run it..
    I kept the mvc folder in my htdocs & called index.php but it directly
    shows the content of index.php rather than showing books list.
    Any help will be appreciated.

    Ibrahim

    22 Jun 11 at 1:21 am

  61. Nice tutorial ONE OF THE BEST

    umer singhera

    25 Jun 11 at 12:08 am

  62. This guide is what I’m looking for. So far I got it from framework and need more for my student, I learn much from this. Thank you very much.

    nike

    26 Jun 11 at 6:37 pm

  63. this is great ………..
    thanks so much……

    Sonu

    27 Jun 11 at 4:10 am

  64. Wow awesome tutorial :)
    MVC is now a lot more clearer to me :)
    Thanks!!

  65. Hi!. this post is very interesting, but… how I can insert records in a Data Base?

    Thanks

    AngelFQC

    8 Jul 11 at 1:31 pm

  66. A very simple and perfect explanation of MVC, for a newbie. Very good job.

    Rahul Sonar

    7 Aug 11 at 9:36 pm

  67. Thank you thousand times. My abc (pre school) of MVC is hear. Very simple and specific. Great work.

    Hirantha

    1 Sep 11 at 6:47 am

  68. Nice Tutorial for MVC

    Ravi Shukla

    5 Sep 11 at 5:34 am

  69. In the book class, the attributes have public access. It is good practice to make these attributes private and have public accessors, e.g. public getTitle(), getAuthor() and getDescription(). However, once this is done, the views, e.g. booklist.php would need to use these methods. I have read in other MVC posts and tutorials that only “simple php” should be used in views. Is the passing of objects to views and the use of more complex php access methods acceptable?

    Gammerz

    8 Sep 11 at 9:42 am

  70. Thank you very much,this is a nice tutorial.The code in view module needs a little explanation i.e how you call the $title in view.

    Muhammad Ali

    18 Sep 11 at 8:25 pm

  71. Interesting very clear, but what about setting and getting how can I implement it? in other tutorial they say set and get is very important Im confused :(

    matt

    5 Oct 11 at 10:23 am

  72. it’s so simple but clear most to illustrate the php mvc, thanks

    feihu it web

    27 Oct 11 at 7:32 am

  73. @Gammerz
    1. First of all this is just an introduction to MVC framework in PHP. Some things might not be the same in “real life”.
    2. I don’t find any reason for which not to use getters/setters in views. This refers to the principle of encapsulation and should be generally valid regardless the layer where you are. Further more if the same object is used in 2 layers encapsulation should be used to a achieve a better degree of decoupling.

    admin

    27 Oct 11 at 3:08 pm

  74. thankssssss it’s a gr8 tutorial

    punit jain

    31 Oct 11 at 10:02 pm

  75. Excelent tutorial, easy to understand and with actually working code.
    This is the best simply-tiny MVC project on the web, the second is KissMVC. It would be great, if someone create next episode of this, with real basic examples of use (or sharing his little project).
    I need create similar framework for my bachelor work, or use this.

    (sorry for my English, i’m from Czech Republic – Central Europe).

    Petr F.

    4 Nov 11 at 10:04 am

  76. Thank you very much for the tutoriel(^-^).

    Tsizehena

    9 Nov 11 at 1:58 am

  77. You really make it appear so easy along with your presentation however I find this topic to be actually one thing that I feel I’d by no means understand. It kind of feels too complicated and extremely broad for me. I’m taking a look forward on your subsequent post, I will attempt to get the grasp of it!

    model search

    14 Nov 11 at 4:31 pm

  78. thank you for this its gooooooooooood

    mostafa

    19 Nov 11 at 1:39 pm

  79. Nice Tutorial!!thanks

    This is actually what I am looking for, not an MVC tutorial around the net which has a lot of nonsense blah blah and you got nothing..

    Thanks!

    Gian

    6 Dec 11 at 12:26 am

  80. Thank you very much,this is a nice tutorial

    yadagiri

    21 Dec 11 at 3:08 am

  81. Its a great tutorial for mvc..

    lovely

    23 Dec 11 at 3:12 am

  82. good but i have few question
    i make a class with name menu. I make three properties and constructor. now i make another class with name model_menu.I want to create my menu class object in model_menu class constructor with value..see below code

    class menu{
    public $a;
    public $b;
    public $c;
    function construct($a,$b,$c){
    some code
    }

    class model_menu{
    public $model_menu;
    function construct{
    i wanna call object of first class here with value of three parameters.
    }

    thanks
    Regard

    fun.maaza

    29 Dec 11 at 12:20 pm

  83. Great tutorial, however I have one question..

    When you use the controller to tell what model what data to give you, how can you pass two different objects back to the controller at once if with return?

    For example in the controller I have buildProfile($userId) and I wish to get $user = new user(); return $user->getUsername(); but I also want to get $comments = new interface(); return $comments->getComments();

    Would it be okay to run both from the controller one after each other or is this missing the point of mvc?

    Dan Thorpe

    5 Jan 12 at 7:28 pm

  84. Thanks, this is best simple MVC tutorial which is i am looking for.

    Excellent job

    Thanks for sharing.

    Govind Krishan Agrawal

    7 Jan 12 at 11:00 am

  85. Great tutorial, easy to understand, just what I was looking for. Sometimes is hard to find this kind of explanations which you need if you’re kind of noob (like me)

    Mosazu

    12 Jan 12 at 1:32 pm

  86. Thank you very much! Out of all the MVC with PHP explaination out there, I think this tutorial is the easy to understand.

    I really don’t like those emphasize too much on .htaccess, folders organization & superclass together into the tutorial. It just complicate things. Should leave the in depth detail of SEO, OO, layered architecture, theory of design pattern etc out.

    inx

    16 Jan 12 at 12:59 am

  87. Thanks a bunch..was looking for this tut for a while now

    gurmeet

    23 Jan 12 at 9:02 am

  88. Is anyone else getting his error? Thanks. Scott U

    Fatal error: Call to a member function on a non-object in /data/webroot/webadmin/app/mvc/controller/Controller.php on line 17

    Scott Dumphrey

    24 Jan 12 at 3:02 pm

  89. Thanks for this posting.the way in which it has been explained with a diagrammatic representation along with some relevant code is worthwhile.

    Bismaya Biswal

    9 Feb 12 at 9:37 pm

  90. very good explanation with practical thanks a lot

    Haider

    18 Feb 12 at 1:01 am

  91. Muito bom este Post, muito bom mesmo.
    Obrigado!

    Mauro Lacerda

    19 Feb 12 at 3:16 pm

  92. I appreciate this, MVC is like pulling teeth trying to adjust to- and my learning style is hands on and this tutorial fits the bill perfectly, thank you.

    Brian

    27 Feb 12 at 8:34 pm

  93. good one

    Ankit

    1 Mar 12 at 4:09 am

  94. Thank you for this clear, concise, simple overview. It is exactly what I was looking for. I’ve been coding PHP for about 13 yrs. I use Objects and Classes and DALs but I’ve never really grokked MVC, no matter how many other articles I’ve read. This hit it home with the exact level of abstraction I needed to start writing with MVC in mind (as opposed to just blindly bashing at code and using a hammer to make it fit into the file structure.)

    your father

    1 Mar 12 at 8:58 pm

  95. thanks buddy this article really help me for getting mvc concept

    jitendra sahu

    3 Mar 12 at 9:55 am

  96. To Tom Quaile and Bruno Cassol:

    It’s so easy to criticize what others do and show off at supergenius … and just do nothing better than what is already done … 2 years later still waiting for their wonderful concepts better than this, for php, not for java … if we are here is because we DO NOT want anything to do with Java …

    Julio Fernandez

    11 Mar 12 at 8:05 am

  97. Man, thank you… This is the first tutorial where my lightbulb just went on … “AHHHH, that’s how MVC works!!!”

    Thanks a lot! :)

    wow thanks

    18 Mar 12 at 10:44 pm

  98. Dear Sir/Madam,
    First and foremost I will appreciate You on writing this awesome tut.Really Speaking from the core of my Heart that i was searching for this from a very long time.Finally my search is over.My suggestion to all viewers is that if they don’t want to use any framework but want to use mvc this is the one of tut they should use.

    Thanks and Regards
    Jhon

    Jhon

    27 Mar 12 at 12:58 am

  99. very good explanation! well done!

    greek

    5 Apr 12 at 4:50 am

  100. very nice explanation

    balaji

    8 Apr 12 at 11:12 pm

  101. Simple. Nobody explained me like this. That clears off my mind and get on with MVC structure.

    I will to write my apps next time around. Thank You.

    bharadwaj.b.g

    9 Apr 12 at 3:45 am

  102. nice and easy to understand…………..

    N.Vijaya

    9 Apr 12 at 4:30 am

  103. such a very good explanation…………

    Vikash

    27 Apr 12 at 1:23 am

  104. Nice little primer here, thanks for this Thanks

    imran

    27 Apr 12 at 12:20 pm

  105. very nice brief and compact overview to jump in, Thanks

    imran

    27 Apr 12 at 12:25 pm

  106. Gracias por el aporte… muy buen tutorial

    Juan Carlos

    29 Apr 12 at 6:07 pm

  107. really is very good
    thanks very much

    Shmed Shaaban Elgendy

    3 May 12 at 6:37 am

  108. Thanks for this, really useful primer to MVC!

    JayB

    8 May 12 at 1:03 am

  109. Very Nice Description… thanks!!!

    Sachin

    10 May 12 at 11:34 pm

  110. 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.

    Edwin

    18 May 12 at 10:17 am

  111. Thanks u very much!

    hi

    19 May 12 at 7:10 am

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

    Matt

    24 May 12 at 9:37 am

  113. Thanks, it’s very clearly.

    suzu

    3 Jun 12 at 11:37 am

  114. 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.

    Ben

    15 Jun 12 at 11:52 am

  115. 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!

    Eddy

    20 Jun 12 at 2:31 pm

  116. 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();

    Adnan

    25 Jun 12 at 12:27 am

  117. really good expanation of mvc thnx

    piyush

    28 Jun 12 at 8:40 am

  118. Superb Explanation..Thank you Guys :-)

    Sajan

    29 Jun 12 at 4:39 am

  119. 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).

    Nitin Deepak

    4 Jul 12 at 9:55 am

  120. 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.

    J

    10 Jul 12 at 12:17 pm

  121. I am new to MVC in PHP and you made it very easy for me to understand the concept.

    Thank You.

    Gunjan

    23 Jul 12 at 12:52 pm

  122. 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.

    Popsana Barida

    3 Aug 12 at 12:58 am

  123. Nice tutoreial

    Vanaraj

    6 Aug 12 at 1:05 am

  124. Nice Tutorial

    Vanaraj

    6 Aug 12 at 1:05 am

  125. Obrigado por compartilhar ta execelente, não só pelo fato de ser novo em mvc.
    mas esta de mais valeu mesmo.

    Francisco

    27 Aug 12 at 11:51 am

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

    Rashid

    6 Sep 12 at 9:51 am

  127. excellent….thank youu..

    sithara

    8 Sep 12 at 10:09 am

  128. Nice explanation,
    i got some useful points from this.

    thanks

    Ravi Bhadauria

    18 Oct 12 at 4:34 am

  129. Thanks for those tutorials.I was looking this type of tutorial now. This MVC explanation is easy to understand.

    Ravi

    22 Oct 12 at 10:38 pm

  130. thanks for the MVC tutorial, best so far

    can you help me linking MVC with REST
    I would be thankful :)

    manish thapa

    23 Oct 12 at 3:40 am

  131. Thanks a lot…. Great tutorial…

    Saswata Sundar

    30 Oct 12 at 9:36 pm

  132. Could you post another example in mvc.

    Kumaresh

    14 Nov 12 at 1:25 am

  133. Simply great, nicely done. Thank you

    Masoud

    19 Nov 12 at 3:31 am

  134. 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.

    PC Technology

    10 Dec 12 at 1:45 pm

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

    Rusty

    20 Dec 12 at 4:44 pm

  136. 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.

    Jeffry

    4 Jan 13 at 10:05 am

  137. very nice tutorial….

    venkatraju

    8 Feb 13 at 3:23 am

  138. 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.

    admin

    12 Mar 13 at 1:57 am

  139. Very good explanation about MVC,
    Thanks for sharing…

    Wey

    22 Mar 13 at 2:09 am

  140. 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.

    Los

    30 Mar 13 at 4:48 pm

  141. Awesome ideas

    Sam

    5 Apr 13 at 11:11 am

  142. great tutorial for one beginning with MVC.

    atul

    9 Apr 13 at 3:29 am

  143. 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.

    Bruce

    16 Apr 13 at 7:39 am

  144. 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

    Blossom

    21 May 13 at 10:47 pm

Leave a Reply