Symfony is based on the classic web design pattern known as the MVC architecture, which consists of three levels:

  • The model represents the information on which the application operates — its business logic.
  • The view renders the model into a web page suitable for interaction with the user.
  • The controller responds to user actions and invokes changes on the model or view as appropriate.

Figure 2-1 illustrates the MVC pattern.

The MVC architecture separates the business logic (model) and the presentation (view), resulting in greater maintainability. For instance, if your application should run on both standard web browsers and handheld devices, you just need a new view; you can keep the original controller and model. The controller helps to hide the detail of the protocol used for the request (HTTP, console mode, mail, and so on) from the model and the view. And the model abstracts the logic of the data, which makes the view and the action independent of, for instance, the type of database used by the application.

The MVC pattern

Figure 2.1 The MVC pattern

2.1.1. MVC Layering

To help you understand MVC's advantages, let's see how to convert a basic PHP application to an MVC-architectured application. A list of posts for a weblog application will be a perfect example. Flat Programming

In a flat PHP file, displaying a list of database entries might look like the script presented in Listing 2-1.

Listing 2-1 - A Flat Script


// Connecting, selecting database
$link = mysql_connect('localhost', 'myuser', 'mypassword');
mysql_select_db('blog_db', $link);

// Performing SQL query
$result = mysql_query('SELECT date, title FROM post', $link);


    <title>List of Posts</title>
   <h1>List of Posts</h1>
// Printing results in HTML
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
echo "\t<tr>\n";
printf("\t\t<td> %s </td>\n", $row['date']);
printf("\t\t<td> %s </td>\n", $row['title']);
echo "\t</tr>\n";


// Closing connection


That's quick to write, fast to execute, and impossible to maintain. The following are the major problems with this code:

  • There is no error-checking (what if the connection to the database fails?).
  • HTML and PHP code are mixed, even interwoven together.
  • The code is tied to a MySQL database. Isolating the Presentation

The echo and printf calls in Listing 2-1 make the code difficult to read. Modifying the HTML code to enhance the presentation is a hassle with the current syntax. So the code can be split into two parts. First, the pure PHP code with all the business logic goes in a controller script, as shown in Listing 2-2.

Listing 2-2 - The Controller Part, in index.php

code.db31827a1890f47f5d6c0d7daee96b43b402dc31php List of Posts