Reputation: 1768
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.
Upvotes: 10
Views: 17264
Reputation: 12192
IMO...
MVC is a very generic design pattern that doesn't necessarily say what is good and what is bad. There's a model, a view and a controller. The responsibilities of each of these things depends on the flavor of MVC, and the flavor of MVC you choose should depend on the complexity of your project. For example, if you have a domain-driven project then the examples given by others here wouldn't work very well.
So at its very base:
Model: An object that has data that will be displayed in the view. Whether it's a DTO or a domain model is not actually defined here, but I'll share my thoughts on this in a second.
View: It is what the user sees and how the user interacts. Any code or logic here should directly support the view. In other words ZERO business logic, ZERO data access logic, ZERO knowledge of anything beyond what the user physically see. Either a web form, a desktop window form, or activity (mobile) etc...
Controller: Probably the most ambiguous piece of this puzzle. One thing is for sure, it mediates between the view and the "model" and also decides what happens next or rather, it 'controls' the flow. But it's important not to take that description too far. What this thing does really depends on your understanding of MVC. So I'll share the way I look at it in a web context; but basically, just draw a line between controlling the flow of the service and actually performing the service.
MVC, to me, isn't a different way of describing N-tier, as some people might claim. There are no layers in MVC as MVC is actually IN your presentation layer. Every element of MVC actually lives in the presentation layer and the MVC pattern just says that you should the separate the concerns between getting the data and displaying it:
If you can accept that statement, then it should help clarify what the model really is in this context. The model is NOT a data access object and the model is NOT a domain model because neither of those things should be in your presentation layer. So that leaves us with either a ViewModel (MVVM) or a DTO. I'm going to go with DTO for the sake of simplicity.
So if we've accepted DTO as the type of model that we're talking about when we say "model" in MVC, then where do we get it? If the controller shouldn't be messing with data access, then where? How about your service layer? Your service layer contains all the "how to" of your application. It is the "Do stuff" layer. So if your view wants to create a user, it'll collect the data and hand it to the controller. The controller decides which service(s) to call in order to accomplish the task and sends it the request with the necessary data. The service layer responds with a DTO. That DTO can either be used directly or added to another model (if there were multiple services called, for example).
The important points are:
Again, this in a web context. If you're working with MVC in an android app, maybe you won't have a service layer or a domain. Perhaps you'll interact with a different breed of objects. Personally, I always use service or application layers, and for several reasons that may or may not be seen as valuable to others.
So in MVC.Net, the controller is more like an API; the view and the API are two different presentation mediums that are meant to work together (the backend controller presents data, the frontend controller builds models with that data and mediates with the view). In Angular, the controller is more like what we're talking about here. Layers of layers of layers, it seems. It's a bit confusing to conceptualize, but the concept never actually moves beyond the presentation layer.
But to summarize: The controller "controls" operations and data going in and out of your system, to and from the view but doesn't actually DO the business. The details of that process depend heavily on your design philosophy for the project.
So here in this diagram, I've grouped the concepts to show MVC within N-tier in a typical monolithic application. The communication runs from left to right and does not jump over any other layer (see: Onion Architecture). In the presentation layer, the controller knows about the model and the view but the view and the model know about nothing for the most part. However, in many flavors of MVC, including ASP.Net and MVVM, the view might know about the model's interface or prototype (but not the model instance) so that it can bind to it.
The controller would handle the manipulation of the model (or view model in this context) which means it may need to know about the domain object and domain services. You can optionally insert an application layer between the presentation layer and the domain if you want a more reusable application (for example, your application could have multiple heads: a web API and a desktop app and a mobile app, etc.) to provide a transactional boundary and further isolation. It's important that the view has no knowledge/dependency on the domain objects in this architecture -- that's why there's a separate model for the view. The point of the model in MVC is to create a model for the view. That is, it is a model specifically designed to serve the view, NOT the domain. It's ok for the view model to wrap/adapt the domain model so long as it's never exposed publicly and/or accidentally serialized.
On a side note, the "presentation layer" in a web API, in my opinion, is the serialized contract (e.g. JSON or XML). So treat that accordingly.
Upvotes: 10
Reputation: 26660
I will try only to answer the question in title. So, what is the role of an controller in MVC?
It's job is to be a model format to view format translator in order not to have UI-driven model and UI-driven database structure.
The idea is to develop the business logic driven database structure and then develop an independent UI. Now when we add or move some UI control our model and database structure shouldn't change.
Upvotes: 0
Reputation: 1520
I think there could be a use for a controller in this case, and ill show the code for it.
MODEL:
<?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);
function getPost() {
return $post;
}
?>
VIEW:
<html>
<head></head>
<body>
<input type="submit" onClick="postToScreen();" value="Post">
<p id="post"></p>
</body>
</html>
CONTROLLER:
<?php
$controllerPost = getPost();
?>
<script type="text/javascript">
function postToScreen() {
document.getElementById("post").innerHTML="<?php echo $controllerPost; ?>";
}
</script>
my javascript is rusty. i think i got that code right but id double check it before putting it in anything. the controller controls what the view looks like, and in certain circumstances, what data the model contains.
Upvotes: 2
Reputation: 9
IMHO in MVC the controller has two main purposes:
In a scenario with much more functionality than in your sample you will see the advantages. But you should decide for or against MVC and use the same approach in every form of you application, don't mix it. I would prefer MVC, you do almost always need controller logic.
Upvotes: 0
Reputation: 143795
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).
Upvotes: 15
Reputation: 11042
model.php is in this case you controller.
The roles of model, view and controller are not easy to distinguish if you don't have a good MVC framework (plain PHP isn't a good one).
The Model is your data structure wich is made persistent in a DB. In terms of code if mainly consists of a data structure as a class.
The View just displays the data. Mainly html with some scripting tags.
The Controller controls what happens. For instance, a user edits a post. The data is received by the controller, maybe modified a little bit (added timestamp, users ip) and sent to the model in order to store it. The controller then decides wich view to display next and what data to fetch for the new view.
Just a small example.
Upvotes: 1