Responsibilities of controller in MVC. How should view access model data through controller? - model-view-controller

I am currently trying to implement my first MVC pet-project. I understand the theory of Model View Controller pattern but when it comes to implementing a real application I am facing several logic issues.
My program is a basic Payment service system (i.e. PayPal).
Here is a typical flow of the program which demonstrates an issue:
Client clicks sign in button in View
A sign in method of Controller is called
This method returns an instance of a current signed in client BACK TO VIEW! (It constructs a client window passing current client as a constructor parameter)
Now when View needs to display some data of that client in client form it just uses that member instance directly.
It seems wrong to me, I think the solution here may be keeping an instance of current logged in user an exclusive private property of controller. But then it may be difficult to display all the data related to that user in View. I think I'll have to crete many 'getter' methods in controller which are going to return strings/strings arrays to populate the UI. It also sounds wrong to me cause I think it's still best to populate the UI with the model data, not some strings received from some controller functions.
What may be the best solution here?
Also, you might be interested in how I implemented MVC pattern in my program in detail.
The model includes Client and Staff entities which inherit the base properties from their superclass BaseUser and the two possible accounts: DebitAccount and CreditAccount which are subclasses of BaseAccount. Then I have a singleton PaymentService which stores all the instances of actors and accounts.
Here is a UML of my model
Then I have a view which is represented by:
EntryForm class — You can register a new client; log in a client or a staff member.
ClientForm
StaffForm — Admin panel
I have sketched/commented what looks like severe design fuckups to me(Sorry for the handwritting).
Here is a UML of my view
And controller
Your help and guidance will be much appreciated!

Related

MVC - Should be there a master View, Model and Controller or should they be implementation-specific?

I'm interested in the concept, not the implementation. Consider a CarBookingRequest scenario where user through an interface requests for booking a car. Let's discuss it under the following constraint and taking only View in perspective by keeping Controller and Model simple:
There is one controller class/code which contains all the functions representing relevant actions
There is one model class/code that deals only with single database with few tables (no other data models)
There can be many interfaces through which a request can be made:
1. Desktop Application
A user clicks a Button that fires the Click event which in turn is pre-programmed to make a call to BookingController with request NewBooking. Something like:
Event OnClick() {
C = New BookingController
C.Request('NewBooking')
}
2. Mobile Application
A user taps a Button that fires the Touch event which in turn is pre-programmed to make a call to the same BookingController with request NewBooking. Something like:
EventListener OnTouch() {
C = New BookingController
C.Request('NewBooking')
}
3. Vending Machine
A user presses a PushButton on the machine that fires the event which is pre-programmed to make a call to the same BookingController with request NewBooking. Something like:
Event OnPress() {
C = New BookingController
C.Request('NewBooking')
}
Assume similar implementation for a Web Interface and Service Interface where the request is made by another system or a scheduled task. Obviously all these implementation are different versions of BookingViews written in very different languages and platform. Now if I knew these implementations beforehand and I am making a Booking MVC, what should be my View, Controller and Model Class like? or how many? and why?
Should I have a "Main" BookingView class that has a function such as:
Function CallController(Command) {
If Command = 'NewBooking' {
Return New BookingController
}
or some good implementation of controller/action registry to fetch appropriate controller
}
and every specific View should in-turn call this function which then will call the BookingController as:
Event OnClick {
C = MainView.CallConroller('NewBooking')
}
Or should each View call the controller separately in its own way?
May be too many questions but I am of the view that my View, Controller and Model should be reusable and every new Interface (Mobile, Machine or Web) should require only their specific handling of the View (events or displays) while the connecting and fetch data code remains untouched.
The core idea of MVC patterns is to separate the three aspects of the application - model, view and controller - from each other.
The way you describe your solution, doesn't seem to adhere to this principle. Let me suggest a method that helps you to achieve good MVC, following these rules. I am describing the generic rules, you can then modify according to the specifics of your application, frameworks etc:
Your controller should not know about the views. This rule helps to separate "view" from control. If you follow this rule, your controller, instead of worrying about types of client, can just return one type of resource (e.g. a JSON resource, in this case a Booking). Then, each client (Web, mobile, machine) has to handle presentation of this resource, whichever way they want. But the important point is that, it is not the concern of controller.
Your Model should not know about the controller. The concern of Model is to implement a car booking. It does not know what is being done with it (like whether a controller wants to access it to then pass it to someone else or so). For example, it may have an interface such as
CarBooking:
constructor();
book();
unbook();
...
It performs the business logic of constructing a request, booking a request or removing a booking. Period.
How do you achieve this, proper separation of Model, View and Controller? Well, one method is to start from within, and then move outward. That is, start from Model, then controller, then view. In reality, you may not do it in this order as you has to consider all of these aspects. But, what I am saying is more in the logical sense.

How should the MVC pattern work?

I have searched and searched but got no answers: How should the MVC pattern work?
So long I got two examples out of many similar ones: one of them suggests that the view should be updated by the controller, but the model is directly updated by the view, and another one suggests that the model should be updated by the controller, but the view should be updated by the model.
I have learned that the view should display content from the model fetched by the controller, and the model content would be altered by the view and updated by the controller.
It's been a year, and I got no answers. Maybe because the question is kinda opinion-based, or maybe because it didn't get much attention.
But ever since then I searched and studied more and more about best practices and design patterns, and now I feel confident enough to answer my own question.
Q: So, how should the MVC pattern work?
A: It should work the way you design it.
The MVC pattern defines three vital types of components: the Model, the View and the Controller:
The Model is what holds and manipulates the data you're working with: it handles persistence methods (writing/reading or CRUD) and has all the properties that your file/database table has;
The View is what displays the Model in a human readable way: it binds his visual components' values to properties of the Model;
Finally, the Controller is what notifies the View of changes on the Model, or notifies the Model of changes on the View: basically it's a sort of messenger, notifying two parts of each others' actions.
Now, how's the usual data flow of a MVC application?
The user changes a component value on the view;
The View queries the Controller about the value that the user passed;
The Controller then notifies the Model that it wants data about the value that the View passed;
The Model interacts with the database and gets the corresponding values (if they exist). After that, it notifies the Controller that it finished whatever it was doing;
The Controller notifies the View that the Model has been updated;
The View updates its' components accordingly, changing whatever values that may have changed.
That was only the reading flow, the writing flow is similar but a bit different:
The user changes values on the View;
The View sends those values to the Controller, saying that data changed and it should be persisted;
The Controller notifies the Model about the data changes, and passes the message along;
The Model then updates the database with the new/updated data, and notifies the Controller;
The Controller notifies the View that the Model has been updated;
The View displays a message to the user, saying that the operation was sucessful.
Now, when I first asked this question, I was with a Java-heavy mindset, so I wanted to know how would I go about implementing this in Java:
DAOs and Java Beans. You write the views and the controllers, but the models are split between data objects (Beans) and persistence objects (DAOs);
Java Beans with embedded persistence methods. You write the views, the controllers and the models. The models are Java Beans that have whichever persistence methods you need (the most basic ones being insert, select, list, update and delete).
So, my final answer is: There's a lot of correct ways of implementing the MVC pattern. But there's a series of guidelines you should follow if you want your implementation to be correct.

MVC, controller - use cases

I've learned that you should set up the controller-class in a MVC-OOD as a use case, from top to bottom in only one method that run the MVC-classes.
Is it OK to use different methods in one controller to get more control and better overview?
Let's say you wanna run a controller that will display a login form (getting the html etc from the View). And the same controller will also display a log-out button IF the user is NOT logged in.
This could be done with a single method in the controller, but using two methods seems better. One method to call if you want the login form, and one to call if you want to log-out button.
(just an example)
So, what does the pros say. Should each controller contain one "use case" method only, or could it be several?
TL;DR -- you have misunderstood the MVC design pattern and are doing it wrong.
Controllers are not responsible for rendering the interface, nor for presentation logic. Controllers do not display anything. Instead, each controller's method deals with different user's request. It extracts the data from said request and passes it to model layer and the associated view.
Decisions about what and how to display are in purview of views. Views contain the presentation logic in MVC pattern. In the context of web applications, views create the response. They can compose a from from multiple templates or just send a single HTTP header.
Controllers can signal the associated view by passing some specific values of the request to that view, but most of the decisions in the view are based on information that the view requested from different services in the model layer.
A Controller's methods are based on what type of requests a user can send. For example in a authentication form it might be: GET /login and/or POST /login.
Its important to remember two things with MVC, firstly, its an Object-Oriented Architecture, and secondly, It should be used for separating concerns.
Separation of Concerns is related to Abstraction, It is to aid us in understanding the section of code at hand. The Model and View are both collections/domains of related objects. Each object is fully complete and relevant to its domain.
You will find objects with types such as Buttons, Images, Text Inputs etc inside your View, and you will find business related objects (User, Account, Profile etc) within your Model.
The collection of objects inside your Model don't tend to do much, They require logic to wire the objects together. (Or simply delegate simple single object requests to the correct object)
The Controller provides the interface into your Model, and contains the business logic related to the Model and the interactions between the Model objects. You will have a single Controller for your Model, and the Controller will have multiple methods which will align with your use-cases.

ASP.NET MVC: Where do you assemble the view model for a view?

From inside to outside, these are our MVC app layers:
MS SQL / Tables / Views / Stored Procs
Entity Framework 4.1 (ORM) with POCO generation
Repository
Service (retrieve) and Control Functions (Save)
Routing -> Controller -> Razor View
(client) JQuery Ajax with Knockout.js (MVVM)
Everything is fine until I need to create a single ViewModel for step 5 to feed both the Razor view as well as the JSON/Knockout ViewModel:
Header that includes all Drop down list options and choices for the fields below
Items - an array of whatever we send to the client that becomes the ViewModel
Since the Controller won't have access to the Repository directly, does this mean I create a service for each and every view that allows editing content? I'll need to get the POCO from the repository plus all options for each field type as needed.
It just seems redundant to create separate services for each view. For example, a viewModel to edit an address and a separate viewModel to edit a real estate property that also has an address. We could have a dozen forms that edit the same address POCO.
To make this question easier to answer, is allowing the Controller direct access to the repositories a leaky abstraction?
Well, so are your controllers going to have code that translates POCOs from Entity Framework into separate view model objects?
If so, then you should move that code to a separate class, and follow the single-responsibility principle. Whether that class is in the "service layer" or not is up to you. And whether you use AutoMapper or not is up to you. But these kind of data mappers should not be part of the controller logic; controllers should be as dumb as possible.
OK, now let's ignore the data mapping problem, and pretend you could always use your POCOs directly as view models. Then you would still want a service layer, because it would translate between
userService.GetByUserName("bob")
in your dumb controller, and implement that in a specific manner by returning
userRepository.Users.Single(u => u.UserName == "bob")
Putting these together, your UserController ends up taking in IUserService and IUserDataMapper dependencies, and the code is super-dumb, as desired:
public ActionResult ShowUserPage(string userName)
{
var user = userService.GetByUserName(userName);
var viewModel = userDataMapper.MakeViewModel(user);
return View(viewModel);
}
You can now test the controller with stubs for both dependencies, or stub out IUserDataMapper while you mock IUserService, or vice-versa. Your controller has very little logic, and has only one axis of change. The same can be said for the user data-mapper class and the user service class.
I was reading an article this morning that you might find somewhat illuminating on these architectural matters. It is, somewhat condescendingly, titled "Software Development Fundamentals, Part 2: Layered Architecture." You probably won't be able to switch from a database application model to the persistent-ignorant model the article describes and suggests. But it might point you in the right direction.
i personally always inject the repository/repositories into the controller. i'm not sure why you would want to have a service layer between the repository and the controller. if anything you would use specifications.
once you've done that, check out automapper. its a mapper that, once properly configured, can map your domain model to your viewmodel, and back again.

What exactly is the model in MVC

I'm slightly confused about what exactly the Model is limited to. I understand that it works with data from a database and such. Can it be used for anything else though? Take for example an authentication system that sends out an activation email to a user when they register. Where would be the most suitable place to put the code for the email? Would a model be appropriate... or is it better put in a view, controller, etc?
Think of it like this. You're designing your application, and you know according to the roadmap that version 1 will have nothing but a text based command line interface. version 2 will have a web based interface, and version 3 will use some kind of gui api, such as the windows api, or cocoa, or some kind of cross platform toolkit. It doesn't matter.
The program will probably have to go across to different platforms too, so they will have different email subsystems they will need to work with.
The model is the portion of the program that does not change across these different versions. It forms the logical core that does the actual work of whatever special thing that the program does.
You can think of the controller as a message translator. it has interfaces on two sides, one faces towards the model, and one faces towards the view. When you make your different versions, the main activity will be rewriting the view, and altering one side of the controller to interface with the view.
You can put other platform/version specific things into the controller as well.
In essense, the job of the controller is to help you decouple the domain logic that's in the model, from whatever platform specific junk you dump into the view, or in other modules.
So to figure out whether something goes in the model or not, ask yourself the question "If I had to rewrite this application to work on platform X, would I have to rewrite that part?" If the answer is yes, keep it out of the model. If the answer is no, it may go into the model, if it's part of the essential logic of the program.
This answer might not be orthodox, but it's the only way I've ever found to think of the MVC paradigm that doesn't make my brain melt out of my ear from the meaningless theoretical mumbo jumbo that discussions about MVC are so full of.
Great question. I've asked this same question many times in my early MVC days. It's a difficult question to answer succintly, but I'll do my best.
The model does generally represent the "data" of your application. This does not limit you to a database however. Your data could be an XML file, a web resource, or many other things. The model is what encapsulates and provides access to this data. In an OOP language, this is typically represented as an object, or a collection of objects.
I'll use the following simple example throughout this answer, I will refer to this type of object as an Entity:
<?php
class Person
{
protected $_id;
protected $_firstName;
protected $_lastName;
protected $_phoneNumber;
}
In the simplest of applications, say a phone book application, this Entity would represent a Person in the phone book. Your View/Controller (VC) code would use this Entity, and collections of these Entities to represent entries in your phone book. You may be wondering, "OK. So, how do I go about creating/populating these Entities?". A common MVC newbie mistake is to simply start writing data access logic directly in their controller methods to create, read, update, and delete (CRUD) these. This is rarely a good idea. The CRUD responsibilities for these Entities should reside in your Model. I must stress though: the Model is not just a representation of your data. All of the CRUD duties are part of your Model layer.
Data Access Logic
Two of the simpler patterns used to handle the CRUD are Table Data Gateway and Row Data Gateway. One common practice, which is generally "not a good idea", is to simply have your Entity objects extend your TDG or RDG directly. In simple cases, this works fine, but it bloats your Entities with unnecessary code that has nothing to do with the business logic of your application.
Another pattern, Active Record, puts all of this data access logic in the Entity by design. This is very convenient, and can help immensely with rapid development. This pattern is used extensively in Ruby on Rails.
My personal pattern of choice, and the most complex, is the Data Mapper. This provides a strict separation of data access logic and Entities. This makes for lean business-logic exclusive Entities. It's common for a Data Mapper implementation to use a TDG,RDG, or even Active Record pattern to provide the data access logic for the mapper object. It's a very good idea to implement an Identity Map to be used by your Data Mapper, to reduce the number of queries you are doing to your storage medium.
Domain Model
The Domain Model is an object model of your domain that incorporates behavior and data. In our simple phone book application this would be a very boring single Person class. We might need to add more objects to our domain though, such as Employer or Address Entities. These would become part of the Domain Model.
The Domain Model is perfect for pairing with the Data Mapper pattern. Your Controllers would simply use the Mapper(s) to CRUD the Entities needed by the View. This keeps your Controllers, Views, and Entities completely agnostic to the storage medium. This also allows for differing Mappers for the same Entity. For example, you could have a Person_Db_Mapper object and a Person_Xml_Mapper object; the Person_Db_Mapper would use your local DB as a data source to build Entities, and Person_Xml_Mapper could use an XML file that someone uploaded, or that you fetched with a remote SOAP/XML-RPC call.
Service Layer
The Service Layer pattern defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation. I think of it as an API to my Domain Model.
When using the Service Layer pattern, you're encapsulating the data access pattern (Active Record, TDG, RDG, Data Mapper) and the Domain Model into a convenient single access point. This Service Layer is used directly by your Controllers, and if well-implemented provides a convenient place to hook in other API interfaces such as XML-RPC/SOAP.
The Service Layer is also the appropriate place to put application logic. If you're wondering what the difference between application and business logic is, I will explain.
Business logic is your domain logic, the logic and behaviors required by your Domain Model to appropriately represent the domain. Here are some business logic examples:
Every Person must have an Address
No Person can have a phone number longer than 10 digits
When deleting a Person their Address should be deleted
Application logic is the logic that doesn't fit inside your Domain. It's typically things your application requires that don't make sense to put in the business logic. Some examples:
When a Person is deleted email the system administrator
Only show a maximum of 5 Persons per page
It doesn't make sense to add the logic to send email to our Domain Model. We'd end up coupling our Domain Model to whatever mailing class we're using. Nor would we want to limit our Data Mapper to fetch only 5 records at a time. Having this logic in the Service Layer allows our potentially different APIs to have their own logic. e.g. Web may only fetch 5, but XML-RPC may fetch 100.
In closing, a Service ayer is not always needed, and can be overkill for simple cases. Application logic would typically be put directly in your Controller or, less desirably, In your Domain Model (ew).
Resources
Every serious developer should have these books in his library:
Design Patterns: Elements of Reusable Object-Oriented Software
Patterns of Enterprise Application Architecture
Domain-Driven Design: Tackling Complexity in the Heart of Software
The model is how you represent the data of the application. It is the state of the application, the data which would influence the output (edit: visual presentation) of the application, and variables that can be tweaked by the controller.
To answer your question specifically
The content of the email, the person to send the email to are the model.
The code that sends the email (and verify the email/registration in the first place) and determine the content of the email is in the controller. The controller could also generate the content of the email - perhaps you have an email template in the model, and the controller could replace placeholder with the correct values from its processing.
The view is basically "An authentication email has been sent to your account" or "Your email address is not valid". So the controller looks at the model and determine the output for the view.
Think of it like this
The model is the domain-specific representation of the data on which the application operates.
The Controller processes and responds to events (typically user actions) and may invoke changes on the model.
So, I would say you want to put the code for the e-mail in the controller.
MVC is typically meant for UI design. I think, in your case a simple Observer pattern would be ideal. Your model could notify a listener registerd with it that a user has been registered. This listener would then send out the email.
The model is the representation of your data-storage backend. This can be a database, a file-system, webservices, ...
Typically the model performs translation of the relational structures of your database to the object-oriented structure of your application.
In the example above: You would have a controller with a register action. The model holds the information the user enters during the registration process and takes care that the data is correctly saved in the data backend.
The activation email should be send as a result of a successful save operation by the controller.
Pseudo Code:
public class RegisterModel {
private String username;
private String email;
// ...
}
public class RegisterAction extends ApplicationController {
public void register(UserData data) {
// fill the model
RegisterModel model = new RegisterModel();
model.setUsername(data.getUsername());
// fill properties ...
// save the model - a DAO approach would be better
boolean result = model.save();
if(result)
sendActivationEmail(data);
}
}
More info to the MVC concept can be found here:
It should be noted that MVC is not a design pattern that fits well for every kind of application. In your case, sending the email is an operation that simply has no perfect place in the MVC pattern. If you are using a framework that forces you to use MVC, put it into the controller, as other people have said.

Resources