MVC Model View Controller

Posted in PHP by

MVC is short for Model View Controller. It is a design pattern from GUI development which is often used in web development.

A modern website written in php5 will benefit from the MVC pattern, because it allows easier maintenance and better results. In this article you will learn about the execution flow and how the different parts interact with each other. Of course there will be hints on how a possible implementation could look like.

MVC flow

  1. A user sends a request to your website.
  2. index.php/query/string/with/params is called.
  3. the router will determine which controller will be called based on the "query/string/with/params". The router can be very simple and just analyse the first part of the query string.
  4. the controller (the one determined by the router) will be called.
  5. In a simple yet powerful implementation the get or post method of the controller (which is just a php class) is called, depending if the request is a simple GET request or a form with method="post".
  6. You are now inside the controller where the output is generated. Access your models to get data from your database. There should not be any sql queries inside the controller (because that is the job of the model or multiple models). There should not be any HTML in the controller, because the view(s) will take care of em.
  7. When all data is fetched and everything is viewed, the output will be sent to the browser. End.

A closer look at the Controller

<php
class HelloCareController extends Controller
{
  //query is a array with 0 => PHP, 1 => MVC
  function get($query)
  {
   //process request
   $category = Category::find($query[0]);
   $page = Page::find($query[1]);
   echo $this->render('article',array('page' => $page, 'category' => $category));
  }

function post($query) { //process $_POST data. //maybe call get($query) } }

The code inside the controller is pretty high level, most of the time it is about fetching data via the models from the database (find(...)) and rendering it in a view.

The controlller is the right place for permission checks and file handling, but we highly encourage to use existing classes that help you working with files and images. Select a library, but make sure it is up-to-date and got an active community around.

the views

<php
echo <<<HEREDOCZ
<div><h2>{$page['name']}</h2>
<b>{$category['name']}</b><br />
<p>{$page['html']}</p></div>
HEREDOCZ;

A view is the only place where you mix html and php. It is more about html. It should only contain display logic, but make sure a designer can handle it. Use "extract($array)" to save yourself a lot of typing.

That's it. More about MVC in the next part.

Published at , Updated at 2011-11-05

next: Strings Heredoc Nowdoc prev: Best Practices Coding Guidelines