I am trying to learn the MVC architecture. But I am not able to understand why you need a controller. See the below code for my model and view.
model.php connects to the database and retrieves the post. view.php will just display the post.
model.php
<?php
$db = mysql_connect("somehostname", "someuser", constant("somepassword"));
mysql_select_db("somedatabase", $db);
$result = mysql_query("SELECT post FROM posts WHERE postid='" . $_POST['id'] . "'");
$row = mysql_fetch_array($result);
$post = $row["post"];
mysql_close($db);
?>
view.php
<?php
require "model.php";
echo $post;
?>
I set my browser location to http://whateverhost/view.php?id=5
This loads post with the id 5. I did not require a controller here. So I am confused why do you need a controller?
Note: Please explain with reference to the above example. I am not a programming geek and learning things like CakePHP, etc. is overwhelming for me.
Edit: It would be great if you can add controller.php to the above code. That would help me in understanding the role of a controller and how it communicates with model and views.
You don’t need a controller because your example is trivial.
An example from a real case scenario:
Suppose you have a CAD application. The CAD application is arranged as MVC. You have:
For example, the user clicks on a square and deletes it. The controller will receive the event from the view, creates an object representing a command (via the Command pattern), add it into a queue for undo capability and executes the command. The command will then modify the model, but the responsibility of translating view events into the complex machinery that modifies the model is under the responsibility of the controller.
Of course you could say, why isn’t the view creating Command objects then? well, nobody forbids you that, but you would end up having presentation logic mingled with operational logic. This goes against good design, although for the most trivial cases, you could live with this design. For example, if your CAD application allows you to display the list of objects both as a 3D representation and as a list of entities, and you could delete from both, you clearly see that either the two views both implement the same logic to handle the command pattern (bad design), or they just channel the same message to a common controller (good design, the MVC).