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.
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.
2.1.1.1. 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
<?php
// 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);
?>
<html>
<head>
<title>List of Posts</title>
</head>
<body>
<h1>List of Posts</h1>
<table>
<tr><th>Date</th><th>Title</th></tr>
<?php
// 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";
}
?>
</table>
</body>
</html>
<?php
// Closing connection
mysql_close($link);
?>
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.
2.1.1.2. 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