MVC: does anyone know a multi view design for MVC? - model-view-controller

I have a system that need two representations of the same model,
and for simplicity i want to use one model, and not keep multiple models - because than my system will suffer from translation errors (the models will not be compatible) that might cause the system to be faulty.
Does anyone know a good design practice for that problem?
For example lets say i have UserList
which contains multiple users.
From one hand i want to see the all of my userlists and the users that
each of them contains. From the other
hand i want to know for each user
which are the userlists that he
belongs to.
I can save this information twice (once from the userlist point of view
and once from the user point of
view..) but that doesn't sounds like
a good practice.
Further more, let's say that the userlist has some properties that can
be configured by the system view of
the model.
How do i let the user view of the model know that there was a
configuration change in one of the
properties (without going threw the
userlist and tell each user what was
the change,or whether there was a
change).
How do i maintain these multiple views of the same model - the system view, and the user view in the same time while prevent the duplication of data and information and the ease of query for the model information and changes in it?

Go on http://martinfowler.com/eaaDev/index.html :
The list on the right gives access to many Presentation Patterns, with everything explained.
Alternatively, if you use java/Swing, each model can easily be used by several views, so you just follow the regular flow... :-)

Related

Generating Navigation for different user types, MVC, PHP

I have this idea of generating an array of user-links that will depend on user-roles.
The user can be a student or an admin.
What I have in mind is use a foreach loop to generate a list of links that is only available for certain users.
My problem is, I created a helper class called Navigation, but I am so certain that I MUST NOT hard-code the links in there, instead I want that helper class to just read an object sent from somewhere, and then will return the desired navigation array to a page.
Follow up questions, where do you think should i keep the links that will only be available for students, for admins. Should i just keep them in a text-file?
or if it is possible to create a controller that passes an array of links, for example
a method in nav_controller class -> studentLinks(){} that will send an array of links to the helper class, the the helper class will then send it to the view..
Sorry if I'm quite crazy at explaining. Do you have any related resources?
From your description it seems that you are building some education-related system. It would make sense to create implementation in such way, that you can later expand the project. Seems reasonable to expect addition of "lectors" as a role later.
Then again .. I am not sure how extensive your knowledge about MVC design pattern is.
That said, in this situation I would consider two ways to solve this:
View requests current user's status from model layer and, based on the response, requests additional data. Then view uses either admin or user templates and creates the response.
You can either hardcode the specific navigation items in the templates, from which you build the response, or the lit of available navigation items can be a part of the additional information that you requested from model layer.
The downside for this method is, that every time you need, when you need to add another group, you will have to rewrite some (if not all) view classes.
Wrap the structures from model layer in a containment object (the basis of implementation available in this post), which would let you restrict, what data is returned.
When using this approach, the views aways request all the available information from model layer, but some of it will return null, in which case the template would not be applied. To implement this, the list of available navigation items would have to be provided by model layer.
P.S. As you might have noticed from this description, view is not a template and model is not a class.
It really depends on what you're already using and the scale of your project. If you're using a db - stick it there. If you're using xml/json/yaml/whatever - store it in a file with corresponding format. If you have neither - hardcode it. What I mean - avoid using multiple technologies to store data. Also, if the links won't be updated frequently and the users won't be able to customize them I'd hardcode them. There's no point in creating something very complex for the sake of dynamics if the app will be mostly static.
Note that this question doesn't quite fit in stackoverflow. programmers.stackexchange.com would probably be a better fit

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()).

MVC: Are Models and Entity objects separate concepts?

I asked here a while ago for some help in understanding MVC, since I'm very new to the topic. I thought I had a decent understanding of it, and this is documented in a blog post I wrote recently on the subject. My understanding basically boils down to this:
Controller: Determines what needs to be done to fulfill a request, and utilizes whatever models it needs to collect/modify as needed. It's basically a manager for a given process.
Views: Presentation only. Once a controller collects what it needs, it creates a specific type of view, hands it the information, and says "show this to the user however you do it."
Models: Behavior of the application. When the controller asks it to extract or modify something, it knows how to do it. It also knows to trigger other models to do related tasks (in my understanding, when a model tries to "vote for something" on StackOverflow, that model knows to ask if a badge should also be granted because of it. The controller doesn't need to care about that).
My question, assuming all of that is more or less accurate, is where do entity objects come in? Are models and entities the same thing, with each object knowing how to persist its own data, or are entities a separate concept that exist on their own and are used throughout the application?
My money is on the latter, since this would allow models to act independently, while all three layers (model, view and controller) could utilize the entities to pass data around as needed. Also, objects and database persistence seem like concerns that should be separated.
To be honest, the more I read about MVC the more confused I get. I'm about ready to just take the core concept (separate presentation from logic) and run with it in whatever way feels right, and not worry too much about the "MVC" label.
Yes!
My money is on the latter, since this would allow models to act independently
You don't want to bind your view to an Entity, because if the view also needs some other piece of data, you would have to it to your Entity. The model is entirely supportive of the view, and is concerned with supporting that view and nothing else.
For example, you show a list of your entities, what other data might you need? Current page number? Total number of pages? A custom message to be displayed?
This is why you should bind to a model, which you can freely add data items to as you need to.
Update
Here is an explanation of MVC in action...
The controller gets all of the data required for the request and puts it into the model. It then passes the model to the view.
The view then deals with the layout of the data in the model.
Each Model can be one entity that contains some methods to control and use its data.
Is it enough?

How to have the controller change its behavior depending on the view?

If from one view a user enters some invalid data, e.g.:
E-mail: bill#apple.com
then i want the controller to:
not place the data into the model
color the text box reddish
not allow the user to save
But it's possible that if the user enters the same invalid data in a different view i want the controller to:
place the data into the model
color the text box reddish
allow the user to save
But it's possible that if the user enters the same invalid data in a different view i want the controller to:
place the data into the model
color the text box bluish
allow the user to save
And it's possible that another view will:
place the data into the model
leave the text box uncolored
allow the user to save
And it's possible that another view will:
auto-correct the data, placing it into the model
color the text-box reddish
allow the user to have
And it's possible for another view to:
auto-correct the data, placing it into the model
update the view with the new data
color the text-box bluish
allow the user to save
[ad infinitum]
Without using n-controllers for n-views, how do i do this?
Update
i was about to ask a new question on stackoverflow, 'How do i have the controller change its behavior depending on the view." But then i realized that i have the exact same question title in use already.
Today's example:
If the entered data is too long for some parts of some of the database tables it will be going into, then perform validation and reject a save.
unless the data is coming from another view. In which case automatically trim certain fields to fit the database rules
unless the data is coming from another view. In which case, require the database to throw it's truncated exception
So many practical problems with MVC that i never see addressed in the books/articles/blogs i've read - it's no wonder i don't use it.
The logic of what has to be done with each view must reside somewhere. I would recommend you empower the view with that information, instead of using multiple controllers, or creating some sort of mapping between view => configuration within a single controller.
I don't know what these views represent in terms of your domain, but it looks like the view seems to be commanding if invalid data can be saved into the model, if auto-correction is permitted, the visual indication for invalid data, etc. Why not empower the view with all that information?
Each of these views would have certain properties.
acceptsInvalidData => boolean, place invalid data to model
requiresAutoCorrection => boolean, auto-correct the data
synchronizeWithModel => boolean, always keep the view in sync with the model
allowsSavingInvalidData => boolean, allow saving of invalid data
invalidDataIndicator => string:color, how to color view for invalid data
Given these 5 properties (maybe missing one or two), the controller can initiate a sequence of actions that will uniquely handle each type of view. The view will have to expose himself or the properties to the controller.
Your examples can be somewhat generalized in the view as suggested, however, some use cases really ask for different controller imho. Also you might try add some logic in models.
Colors are straight view thing, controllers should decide if it is reasonable to save the data in the models, if that data doesn't have some property deciding if it should be saved or not, let it on controllers, possible different ones. Auto-corrections should be in views and helpers.
That is only my opinion.
To summarize the problem:
It seems you want N different behaviors without having N controllers.
You don't want to tightly couple the views and the controllers (no 1<->1 relationship), but the you want the controller to have strong and varied control over the behavior of each view.
Let me state this differently:
It seems you want N different behaviors without having N objects.
You don't want to tightly couple the A objects and B objects (no 1<->1 relationship), but the you want B object to have varied tight control over the behavior of each A object.
Here's how I see these 2 issues:
This isn't a problem of MVC, its a classic software problem: you either need N objects to have N different behaviors, or you need to parameterize the behaviors so that you can distill out commonality (e.g. the approach Anurag suggested) to have less than N separate objects and/or resort to a giant case statement. :-)
This one isn't a problem of MVC, but rather its one of the trade-offs. MVC has us decouple the M, V, and C code to ease future changes (e.g. changing or adding views). But the trade-off isn't free, the components necessarily have to have less knowledge and control of each other. Either you give up on the controller having tight control over the views (no N different kinds of behaviors) or you give on the segregation between the C and V (e.g. allow 1<->1 tightly coupled views-controllers).
Certainly, there has been great success with MVC in decoupling the Ms from the Vs and Cs, but less success in decoupling the Vs and Cs from each other. I think today's responsive interfaces call for coupling views and controllers, or started differently, its not worth the effort and complexity to strongly isolate views and controllers. This modified M(VC) approach has worked much better for me in the real world.

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