Where to store feedback UI data in ASP.NET MVC 2? - model-view-controller

I'm really new to both ASP.NET MVC and the MVC pattern generally.
For context, I'm currently running .NET 4.0, MVC 2.
I know that MCV 2 has a bunch of built in features for:
validation (both client and server side, through a variety of ways)
error handling (via attributes and other methods)
But what should be used to return feedback to the user that is neither an error nor validation?
For example, I have a simple form that returns a csv (using myController.base.file()) IF data is found.
If data is not found, I'd like to return the View with the Model as-is plus a message, like, "no data found, try a different date range"
Now,
should that kind of feedback message be stored in the model itself?, or
is there a cleaner mechanism for this?
Is that what the ModelStateDictionary is for?
UPDATE
just to clarify. I know there may be many ways to do what I want, but what's the correct MVC way of doing it.
Keep in mind the feedback data is not an error, and I don't want to redirect to some other view.

I think what might clear the air is the idea of a ViewModel. Except for the most simple scenarios, you'll find more than one kind of model in your project. They can go by many names, but I find these names helpful:
Pure domain models (Models)
This is where you have your ideal representations of our data model.
Application models (ViewModels)
These models account for the realities of displaying your domain model in a view. They contain data specifically needed for a specific view. It's perfectly acceptable to put something like a status message in this kind of a model.
I would recommend this insightful blog post which shows when, why and how to use ViewModels.
Example:
public class WidgetDataExportViewModel {
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public MyEnum SomeOtherProperty {get;set;}
public string StatusMessage {get;set;}
public IEnumerable<Widget> Widgets {get;set;}
}

If you're talking about a message that you want to code for somewhere in your view, you ought to have that on your model and have your view consume it.
If you want to be able to handle system messages generally in the same way across your application (with a message at the top or side of the window, e.g.), you might create a utility method that puts the information in ViewData with a special key that could get picked up by your master page. If you use TempData instead, the message could be persisted across a redirect.

I have previously used ModelState.AddModelError successfuly to show a summary message. Just make sure you use a key that is not a Model field name.
Note: I have adapted my design from Steven Sanderson's book (see the index on RulesException)
Good luck

Validation errors directly stemming from user actions on your model (e.g. too short a password)
is at home as close to the model as possible.
General error messages of the "no data found" kind are easier addressed through having a dedicated Error View of some sort.
Added:
If I understand you correct, you prefer to stick with one view; be it validation gold or burning SQL servers ;-)
Not madly MVC2 experienced mysef, but being consistent and always create own models, never what you might be served by what(not) ORM you're using (Linq<->SQL, EF) should give you the fine-graininess you need.
If my memory serves me correct I think the Nerddinner could be enlightening; and if you really
want to take the plunge, why don't go Deep Inside ASP.NET MVC 2 Model Metadata and Validation
I've gotten my MVC mainly from books, but the blogosphere has definitely started producing golden material on the more "foreign" parts of ASP.NET MVC.
My real aha moment regarding the M of MVC came while reading
Steve Michelotti's ASP.NET MVC View Model Patterns (a great source for MVC2 info all round)

Related

Lost in a simple MVC case - how do I return multiple Users?

I'm not sure which title would be more descriptive, so I kept it this way. I feel kinda lost in the world of MVC.
FYI: I use PHP, but that doesn't seem of much importance in this particular case.
My problem is as follows:
I have a UserController containing the following methods:
login
new
show
overview
Then I have my UserModel, containing - in this case - roughly the same methods:
login
create
fetch
The problem is: what do I keep my user data in once fetched from the database (or XML feed, or webservice, or whatever...)? I thought of a User 'business object', containing all (relevant) properties from the database. Then, when fetching the users from the database, I instantiate a new User object for each user I fetch. If only 1 user returned from the search, I return only the User object. If more users get returned, I instantiate a UserCollection object containing all User objects - in which case I can iterate over them, etcetera.
Is that a correct way of dealing with users in MVC?
And then: imagine I made an overview of 10 users. 5 of them get edited at once - imagine a status modification using checkboxes. How do I process the changes? Do I loop over all changed User objects and store them back in the database? Then it would start to look like an implementation of the Active Record Pattern, something I'm told not to use.
I hope someone can clarify which classes and/or methods I'd need to solve this 'architectural' problem.
Since it is a rather lengthy discussion. I will give the link to an article that I have written on MVC, trying to explain it in simple terms. You may want to take a look at it.
What is MVC pattern about?
If I understand correctly, your UserModel is a bit off;
the Model part of MVC is intended as a programmatic representation of the real world model.
Meaning- it represents all the properties and actions of the real-world subject. The classic example is the Car class, which has properties such as Wheel, CurrentSpeed, and actions such as GoForward(), GoReverse() etc..
So, in your case, I think your model should be what you described as a 'user business object'.
Your controller would be responsible for fetching the UserModels from storage (or wherever), and updating them back.
your workflow would be something like this:
View would call the Controller's GetUsers.
Controller goes to storage, and fetches a list of UserModels.
Controller returns them to the view.
View displays them in some way.
And the other way around for updating.
The UserModel class would be responsible for logic that pertains to individual users (for example- ChangePassword()).

Is Model-Glue's model in Coldfusion the same as the model in other MVC frameworks?

If you follow the quickstart guide provided by the official Model-Glue docs, found here:
http://docs.model-glue.com/wiki/QuickStart/2%3AModellingourApplication#Quickstart2:ModelingourApplication
It will seem like the "model" is a class that performs an application operation. In this example, they created a Translator class that will translate a phrase into Pig Latin. It's easy to infer from here that the program logic should also be "models", such as database operation classes and HTML helpers.
However, I recently received an answer for a question I asked here about MVC:
Using MVC, how do I design the view so that it does not require knowledge of the variables being set by the controller?
In one of the answers, it was mentioned that the "model" in MVC should be an object that the controller populates with data, which is then passed to the view, and the view uses it as a strongly-typed object to render the data. This means that, for the Model-Glue example provided above, there should've been a translator controller, a translator view, a PigLatinTranslator class, and a Translation model that looks like this:
component Translation
{
var TranslatedPhrase = "";
}
This controller will use it like this:
component TranslatorController
{
public function Translate(string phrase)
{
var translator = new PigLatinTranslator();
var translation = new Translation();
translation.TranslatedPhrase = translator.Translate(phrase);
event.setValue("translation", translation);
}
}
And the view will render it like this:
<p>Your translated phrase was: #event.getValue("translation").TranslatedPhrase#</p>
In this case, the PigLatinTranslator is merely a class that resides somewhere, and cannot be considered a model, controller, or a view.
My question is, is ColdFusion Model-Glue's model different than a MVC model? Or is the quickstart guide they provided a poor example of MVC, and the code I listed above the correct way of doing it? Or am I completely off course on all of this?
I think perhaps you're getting bogged down in the specifics of implementation.
My understanding of (general) MVC is as follows:
some work is needing to be done
the controller defines how that work is done, and how it is presented
the controller [does something] that ultimately invokes model processing to take place
the model processes handle all data processing: getting data from [somewhere], applying business logic, then putting the results [somewhere]
the controller then [does something] that ultimately invokes view processing to take place, and avails the view processing system of the data from the model
the view processes grab the data they're expecting and presents that data some how.
That's purposely very abstract.
I think the example in the MG docs implement this appropriately, although the example is pretty contrived. The controller calls the model which processes the data (an input is converted into an output), and then sets the result. The controller then calls the view which takes the data and displays it.
I disagree with the premise of this question "Using MVC, how do I design the view so that it does not require knowledge of the variables being set by the controller?" The view should not care where the data comes from, it should just know what data it needs, and grab it from [somewhere]. There does need to be a convention in the system somewhere that the model puts the data to be used somewhere, and the view gets the data it needs from somewhere (otherwise how would it possibly work?); the decoupling is that model just puts the data where it's been told, and the view just gets the data out from where it's been told. The controller (or the convention of the MVC system in use) dictates how that is implemented. I don't think MG is breaking any principles of MVC in the way it handles this.
As far as this statement goes "In this case, the PigLatinTranslator is merely a class that resides somewhere, and cannot be considered a model, controller, or a view." Well... yeah... all a model IS is some code. So PigLatinTranslator.cfc models the business logic here.
And this one: "In one of the answers, it was mentioned that the "model" in MVC should be an object that the controller populates with data, which is then passed to the view"... I don't think that is correct. The controller just wrangles which models and which views need to be called to fulfil the requirement, and possible interchanges data between them (although this could be done by convention, too). The controller doesn't do data processing; it decides which data processing needs to be done.
Lastly, I don't think the "strongly-typed" commentary is relevant or an apporpriate consideration in a CF environment because CF is not strongly typed. That is a platform-specific consideration, and nothing to do with MVC principles.
I think one of the common confusions around MVC is that there are multiple Views, multiple Controllers but only one Model. cfWheels has a "model" object for each persistent domain object which I think is very confusing - but of course cfWheels is drawn from Ruby on Rails which also uses "model" in that context.
In general, in MVC, "The Model" represents your business data and logic as a whole. The Model is made up of a number of domain objects (which are typically persistent) and a number of service objects (which exist to orchestrate operations across multiple domain objects). In real world applications, you typically have a data layer that manages persistence of domain objects - which may be partitioned in a number of ways.
It may also help to think of the input data that the view needs as it's "API" and it is the controller's job to satisfy that API by providing compatible data. Think of it more that the controller needs to know what type of data will satisfy the view rather than the other way around.

Getting started with software design using MVC, OO, and Design patterns [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
NOTE:
This question has been updated to provide more detail and insight than the previously.
UPDATE:
I just want to say thank you to everyone who responded. I'm still pretty much in the dark on what design pattern would work best for the Widget. Perhaps one of the Factory or Builder patterns?
I am just getting started on a new project and need to use MVC, OO and design patterns.
Here's the idea: Imagine a page that displays a set of widgets. These widgets are (usually) charts that are based off of data contained in several separate tables in the database. I use a running example of page that reports on a student's performance.
High Level Requirements
a page that displays a set of (HTML only) widgets.
widget's data will be based off a database query.
the page can be used to view separate datasets containing similarly laid out data. For example, a single page will display widgets that report on various aspects of a single student's performance.
want to see another student's performance, pull up another page. Displaying different widgets for different students is not needed (though it may be nice to have later).
There may be many students, but data contained in the database is similarly laid out for all students.
the way a widget is displayed may be changed easily (say changing a widget from displaying as a pie chart to display as a bar chart).
widgets should be able to be created quickly.
Low Level Requirements
Currently data does not change so widgets will not need to automatically update themselves.
Widgets may represent a ratio of two things (eg. a ratio of failed tests to successful tests as a pie chart), a series of points, or sometimes a single numeric value.
Development of new widgets should be a breeze, existing code need not be modified.
Framework to be used: Zend Framework, based on MVC.
There are (minimally) three things to define a widget: the dataset to report on (in the example above, the student ID), the query that describes the metric being reported, and a render mode (barchart, timeseries etc).
Here is a pass at breaking down the responsibilities of each layer of the MVC:
View: Zend views are HTML templates with PHP injected. They will contain one of several types of widgets. Widgets are of various forms including: static JPEG images (loaded from a remote site ie: <img src="http://widgetssite.com?x=2&y=3"/>, JSON based javascript widgets, or charts of various kinds (piechart, bar chart etc.)
Controller: Creates the widgets, assigns them to the view afterwards. The set of widgets that is to be displayed on a page needs to be maintained somewhere. Since I can't think of a good way to do this in the view, I'll add this to the controllers responsibilities for now. If there's a better place for this please shout. The controller will also have to handle any other input parameters and passing them to the widget. For example, the data_set id which may be passed at the url line as http:/.../report/?student_id=42
Model: The model, in the Zend Framework, is responsible for pulling the data and as such will most likely contain a class for each widget for accessing the database.
Some points:
The model here, represents the data for a particular widget. So necessarily, it will need to know what the query is going to be, in order to pull together the tables necessary to fetch that data.
There's an additional processing step that will most likely be necessary before the widget can present the data. This is dependant upon which renderer will be used. Sometimes it may require forming a url out of the data returned. Other times, a JSON array. Other times perhaps creating some markup. This can go either in the model or the controller or the view. Unless anyone can think of a good reason to move it to the controller or view, it is probably best to let this live in the model and keep the view and controller thin.
Likewise, a widget will be made up of 3 things, its parameters, its data, and its renderer.
One big part of the question is: What's a good way to represent the widget in an Object Oriented design? I already asked this once, couldn't get an answer. Is there a design pattern that can be applied to the Widgets that makes the most sense for this project?
Here's a first pass at a rather simple class for the Widget:
class Widget{
//method called by the view
render() {//output the markup based on the widget Type and interleaved the processed data}
//methods called by the controller:
public function __construct() {//recieve arguments for widget type (query and renderer), call create()}
public function create() {//tell the widget to build the query, execute it, and filter the data}
public function process_data() {//transform into JSON, an html entity etc}
//methods called by the model:
public function build_query() {...};
public function execute_query() {...};
public function filter_data() {...};
}
Looking at it, I can already see some problems.
For example, it is straightforward to pass the widget that was created in the controller to the View to render.
But when it comes to implementing the model it seems not so straight forward. Table Gateway Pattern is simpler to implement than ORM. But since table gateway pattern has one class for each model/table it doesn't seem to fit the bill. I could create a model for a particular table, and then within that, instantiate any other models needed. But that doesn't seem so to fit the Table Gateway Pattern, but rather ORM pattern. Can Table Gateway Pattern be implemented with multiple tables? What alternatives are there? Does it make sense that the controller creates the widget and the widget creates the Model?
Another issue that arises is that this design does not enable ease of widget creation. ie. Say I wanted to create a PiechartWidget, how much code can be reused? Would it not make more sense to use some OO ideas such as an interface or abstract classes/methods and inheritance?
Let's say I abstract the Widget class so only the shared methods are defined concretely, and the rest are declared as abstract methods. Revising the Widget class to make it abstract (second pass):
abstract class Widget{
private $_type;
private $_renderer;
//methods called by the controller:
//receive arguments for widget type (query and renderer),
protected function __construct($type, $renderer) {
$this->_type = $type;
$this->_render = $renderer;
$this->create();
}
//tell the widget to build the query, execute it, and filter the data
private function create() {
$this->build_query();
$this->execute_query();
$this->filter_data();
}
//methods called by the model:
abstract protected function build_query();
protected function execute_query() {
//common method
}
abstract protected function filter_data();
//method called by controller to tranform data for view
//transform into JSON, an html entity etc
abstract protected function process_data();
//method called by the view
//output the markup based on the widget Type and interleave the processed data
abstract protected function render();
}
Is this a good design? How could it be improved?
I assume writing a new widget will require at least some new code to build the query, and maybe filter the data, but it should be able to use preexisting code for almost all of the rest of its functionality, including the renderers that already exist.
I am hoping anyone could provide at least some feedback on this design. Validate it?
Tear it apart. Call me an idiot. That's fine too. I could use any forward traction.
A few specific questions:
Q1. What's the best way to implement the renderers, as part of the Widget class or as a separate class? 1a. If separate, how would it interact with the widget class(es)?
Q2. How could I improve this design to simplify creation of new kinds of widgets?
Q3. And lastly, I feel like I am missing something here with regards to data encapsulation. How does data encapsulation relate to the requirements and play out in this scenario?
For #2, if you are using WPF on windows, or Silverlight in general, consider using MVVM pattern (Model-View-ViewModel), here is explanation with a WPF implementation:
MVVM at msdn
For #1 (comments not answer): For exact implementations (and minor variations) of MVC, it really depends on what language you are using.
Another alternative to MVC is MVP Model View Presenter
Remember the goal of OO is not to cram design patterns into your code, but to create maintainable code with less bugs/increased readability.
High Requirements
- a page that displays a set of widgets. widgets are based off of data contained in several separate tables in the database.
- widget's data will be based off a database query. widget display its data in a particular way.
- widgets should be able to be created quickly.
Low Level Requirements
- Data changes, multiple charts need to change, push model (from data to ui)
- Development of new widgets should be a breeze, existing code need not be modified
Advice from design patterns basics
- MVC supports one to many notification pattern, so yes, once your widget is initialized, created and connected to the web page, it should wait for notifications from the database.
- Strategy pattern, your entire code should develop to a interface. New widgets should be added to a parametrized LinkedList (or some other data structure). That way new widget developers just implement the interface and your framework picks up these notifications without change to existing code.
Siddharth
The purpose behind all of these ideas -- MVC, patterns, etc. -- is essentially the same: every class should do one thing, and every distinct responsibility in your application should be separated into distinct layers. Your views (page and widgets) should be thin and make few if any decisions other than to present data gathered from the models. The models should operate on a data layer agnostically, which is to say they should not know whether the source of their data is a specific kind of data source. The controllers should be thin as well, acting basically as a routing layer between the views and models. Controllers take input from the users and perform the relevant actions on the models. The application of this concept varies depending on your target environment -- web, rich client, etc.
The architecture of the model alone is no trivial problem. You have many patterns to choose from and many frameworks, and choosing the right one -- pattern or framework -- will depend entirely on the particulars of your domain, which we have far too few of here to give you more specific advice. Suffice it to say it is recommended you spend some time getting to know a few Object-Relational Mapping frameworks for your particular technology stack (be it Java, .NET, etc.) and the respective patterns they were built on.
Also make yourself familiar with the difference between MVP and MVC -- Martin Fowler's work is essential here.
As for design patterns, the application of most of the standard GOF patterns could easily come into play in some form or another, and it is recommended you spend time in Design Patterns or one of the many introductory texts on the subject. No one here can give specific answers as to how MVC applies to your domain -- that can only be answered by experienced engineers in cooperation with a Product Owner who has the authority to make workflow and UI decisions that will greatly affect such decisions in their particulars.
In short, the very nature of your question suggests you are in need of an experienced OOP architect or senior developer who has done this before. Alternatively give yourself a good deal of time in intensive study before moving forward. The scope of your project encompasses a vast amount of learning that many coders take years to fully grasp. This is not to say your project is doomed -- in fact you may be able to accomplish quite a lot if you choose the right technology stack, framework, etc., and assuming you are reasonably bright and focused on the task at hand. But getting concepts as broad as "MVC" or "OO" right is not something I think can be done on a first try and under time constraints.
EDIT: I just caught your edit re: Zend. Having a framework in place is good, that takes care of a lot of architectural decisions. I'm not familiar with Zend, but I would stick to its defaults. Much more depends here on your ultimate UI delivery -- are you in a RIA environment like Flash or Silverlight, or are you in a strict HTML/JavaScript environment? In either case the controllers should still be thin and operate as routers taking user requests from HTTP gets and posts, and immediately handing off to the models. The views should remain thin as well and make as few decisions as possible. The concept of MVC applied in a web environment has been pretty well established by Rails and the frameworks that followed, and I'm assuming Zend is similar to something like CakePHP in this regard: the application server has a routing system that maps HTTP calls to controller actions that respond with specific views. The request/response cycle is basically this:
User request posted through a URL
Router hands control to a controller class
Controller makes a call to a model with the given params
The model operates on the data, posts back to the controller
The framework maps the finished data into a view, with some kind of code-behind that puts the results of the request in the view's scope.
The framework creates html (or xml or whatever) and posts back to the caller.
It sounds like you want to use MVC and other patterns because they are the new buzz words. Splitting your design among model view and controller should tell you how to spread the functionality of your application. Although I totally agree that using MVC is the correct approach, I suggest you research the pattern and look at some source code that implements it. As a start to your question though, the widgets that will be displayed will be your views, that much should be obvious. Input from the user, such as changing a parameter of some widget or requesting other information will come into your application and should be handled by a controller. A concrete example of this is a Java-based HttpServlet. The controller servlet receives the user request and asks the lower layers of your app (Service, Persistence, etc) for an updated representation of your model. The model includes all of your domain-specific objects (i.e the data from your databases, etc). This data (the updated model) comes back to the controller, which in turn pushes out a new view for the user. Hopefully that is enough to get you started about designing your app.
As further help, you could consider using a framework to assist in the development of your app. I like Spring a lot, and it has a first class MVC implementation that really helps guide you to designing a correct MVC web app.
You may consider using Subject Observer Pattern
Have your class, named DataReader as single Subject. Your multiple widgets will act as Observers. Once your DataReader receives data from server, it (Subject) will inform multiple widgets (Observer).
Your individual widgets may have different presentation to present to same set of data from DataReader.
Update
In the message where subject notify observer, you may include the message type information as well. Widgets will only process message type, which is within their own interest, and ignore rest of the message.
NOTE: This is my new answer based on new the updated question.
Here is a proposed class diagram. I'm going to work on a sequence diagram.
My old answer is here:
Based on the requirements you describe, your model is your database or data warehouse and your views are your pie charts, bar graphs, etc. I don't see the need for a controller, because it sounds like you have a one page dashboard with widgets.
You need to spend your time on the database model. Since you're doing all selects and no updates, go for a de-normalized data model that makes these queries efficient. You should put the results of these queries in a table type object (e.g. 2-dimensional array) or 3-dimensional array based on the amount of dimensions. You are limited to 3 dimensions unless you use animation.

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.

MVC: Data Models and View Models

I've read some MVC advice in the past regarding models stating that you should not reuse the same model objects for the domain and the view; but I haven't been able to find anyone willing to discuss why this is bad.
It is my opinion that creating two separate models - one for the domain, one for the view - and then mapping between them creates a lot of duplication, plus tedious mapping code (some of which might be alleviated by things like AutoMapper) that will likely be error prone.
What makes having a separate model for the two concerns worth the trouble of duplication and mapping code?
At its heart, two models is about Separation of Concerns. I want my View to work off of a single Model. I want my Domain Model to represent the conceptual model I build with the domain experts. ViewModel often has technical constraints. Domain Model is about POCO, and not being bound by technical constraints of either data shown (View) or persisted (in a DB or otherwise).
Suppose I have three entities shown on a screen. Does that mean I need to force a relationship between the three? Or just create a ViewModel component object that contains all three items. With a separate ViewModel, View concerns are separated from my domain.
why? 'cause the view shouldn't have the ability to use the model object!
Imagine you pass the project to a web designer to do the view layer. Suddenly he/she has the ability to mess around with your application's data through the model layer. That's not good.
So always only pass the data the view needs, instead of the object with methods.
J.P. Boodhoo's article Screen Bound DTOs will help you understand the design benefit.
There is also a security benefit that I have written about.
Having a presentation model simplifies your views. This is especially important because views are typically very hard to test. By having a presentation model you move a lot of work out of the view and into the domain->presentation model. Things like formatting, handling null values and flattening object graphs.
I agree that the extra mapping is a pain but I think you probably need to try both approaches in your specific context to see what works best for you.
There are even plainer concerns including the view model's ability to be specially formatted and certainly null-safe.
I guess the idea is that your domain models might extend to other implementations, not just your MVC application and that would break the seperations of concerns principle. If your View Model IS your domain model then your domain model has two reasons to change: a domain change requirement AND a view requirement change.
Seems I have duplication of rules as well.
ie. client object validation on the UI, then mapping to domain object that has to be validated.
What I tend to do however is map my set of domain objects to create a model - ie. a webpage that shows customer info, stock info, etc... my model becomes a structure that holds a Customer object and a Stock object.
CompanyPageModel
public Customer Customer{get;}
public Stock Stock {get;}
then in my mvc project ViewData.Model.Customer.Name ViewData.Model.Stock.CurrentStocks
Separation 'seems' like more work, but later, it's good to have this division of UI/Domain model...sorta like writing tests :)
I have drunk the cool-aide finally, I do like being able to mark my viewmodel with display instructions and have that all auto wired up.
What I demand now is some kind of auto generator of viewmodels from poco entities. I always set some string as an int and it takes me forever to find it. Don't even think of doing this without automapper unless you like pain.

Resources