If you persist data in a relational database and use the MVC or HMVC architectures, would a table correspond to a model? If not, what would you call that type of object? I've been hearing debates where some people call them domain objects and others don't differentiate the two.
I've been hereing debates where some people call them domain objects and others don't defferenciate the two
--> That's because this doesn't matter at all. Domain eg. from mathematics can be seen as the model because it defines the data type, range, complexity, ... = the set of possible values for your logic or function. This is mostly identical to a model. In addition to that this does not change anything to call them domain objects or model entities or whatever. The Model (in MVC world) is a concept. The way you define/implement your model is completely up to you as soon as you maintain the separation with the other layers and fits the concept.
Related
Wouldn't creating ViewModels lead to redundancy? In the sense I have my domain model and I need to display the data from it on a view. So we create ViewModels, add DataAnnotations to it and display it on the View. At this point I have 2 object with almost identical data.
As others have already said, only the most trivial application can get away with passing their domain models directly to the view. Even then, it's still not a good idea for a lot of reasons.
The requirements of your view are different from the requirements for your data model. For instance, you may have a field that is required in your view, but is nullable in your vie model. If you add a `[Required]' attribute, then your model will now consider this field non-nullable.
However, my single biggest reason for never using domain models in views is for security. MVC allows you to post any value to it, and the default model binder will happily plug values you post into the model, which means if you had an IsAdmin flag, and someone posted a true value for IsAdmin, then when you saved the changes to the model, someone is now an admin.
The first rule of web security is never trust input from the user, and passing your view models directly to the view basically gives up sanitizing your data.
Yes, it is a form of redundancy. But redundancy is often required to achieve other goals. In case of Models, having this separation of view models and domain models helps in achieving a decoupled setup between your view and data-store. And it is not often that ViewModels are exact copies of Domain.
Which means, either can change without having an impact on other. I can see cases where this would be valuable - data-type changes in table need not call for deployment of the web application.
So, in summary, while there is redundancy, it is a design choice on whether the system is complex enough to benefit from this redundancy.
In 99% cases ViewModels don't lead to redundency.
The only 1% which comes to my mind is simple application with anemic domain models and pages, which shows nothing but a single model on a page. This is peculiar to content management pages.
In any other case:
1) your ViewModels will join information from multiple domain models
2) you'll have a logic specific to your domain in domain models
3) it's not a good idea to mix view-specific metainformation like DataAnnotations into your domain
Nope, using ViewModel has its own purpose. Let's think about a situation when your view has two or more Entities from the Domain Model, without a ViewModel, how are you gonna organize data? The data needed for a view sometime is not exactly like domain model, it can has
less or more information and sometime we have to pre-process data from domain before rendering view(e.g. format date time depends on client's culture).
Furthermore, ViewModel help de-couple the Web UI from the domain layer. Entities in Domain Model is not just about data representation(which is the only purpose of view model), they also have operations that mimics the business rule, you don't want expose too much domain knowledge to the UI layer who doesn't need to know.
I'm using MVC model for 5 months. I agree with MVC, good technique for organizing mind. But every time I try to write model I write module, that confusion rised a question, why it is model, not data or database or storage or etc. Most irrelevant and generic name is model.
I'm okey with view, but controller should be logic or router I think.
From wikipedia:
The pattern isolates "domain logic"
(the application logic for the user)
from the user interface (input and
presentation)
The model manages the behavior and data of the application domain
The controller receives input and initiates a response by making calls on model objects
Why we use model, view and controller as name of this pattern?
The text you quoted (with the emphasis shifted a bit) states that "The model manages the behavior and data of the application domain." Behavior can be defined within the database as stored procedures, but it's much more common for it to be coded either completely or at least partially in the application's host language (C/C++/C#/ASP/Perl/PHP/whatever).
"Model" and "database" are not interchangeable terms - the model is much more than just the database and it does much more than just storing the data.
I concur with Dave's point: but maybe I can add to it a bit...
You should remember that the layers should not know anything more that one level below it...
In my case, the controller does a request to a model: this happens to require a database view joining two separate databases... BUT it's good practice (the only real practice in MVC?) that the controller should never know this - all it needs to know is that when it asks for a model, the model knows how to get it.
That's the point. The model models a "thing", and the controller should make a point of not knowing HOW it gets the "thing".
Ironically, I find this becomes easier to understand when you add an optional but recommended extra layer in as well: Database abstraction.
This adds another layer to the separation. You see this when installing programs (Such as Moodle), which ask you what type of database connection you use. It knows how to talk to databases, but exactly what language it uses is hidden from the Model.
In normal usage: The controller asks for a model, the model asks the database abstraction layer for the results.
When you change from MySQL to MSSQL / XML / carrier pigeon, the model requires no changes.
THAT explains why the model isn't the "database model". It's actually not to do with a database.
In a well designed application, the data is called a "data model" The reason is that we structure the data in what's called a model, because it's "modeling" the business concepts (for example, and order may have order detail lines, or a Person maybe a customer or an employee)
This is why it's called the Model, because it's typically an abstraction of the real data structure, and it is typically agnostic as to how it's stored (database, flat files, in memory, punched tape, carrier pigeon... whatever..)
It's a generic concept because the Model should not be specific about it's implementation detail.
Hey guys - here's a question on Zend Framework or better on MVC in general:
I am asking myself for a quiet a long time now, if it is a good idea to push business objects (User, Team, etc.) to my views or if it would be better just to push dump data containers such as arrays to the view for rendering.
When pushing business objects to my view I have a much tighter coupling between the views and my domain model, however, the view could easily do things like foreach($this->team->getUsers() as $user) { ... } which I personally find very handy.
Providing domain model data in dumb arrays to me looks more robust and flexbile but with the costs of that the view cannot operate on real objects and therefore cannot access related data using object's method.
How do you guys handle that?
Thanks much,
Michael
It's better to make your View access a Domain Model object in an object-oriented manner, instead of using the Controller to convert Model data into plain scalars and arrays.
This helps to keep the Controller from growing too fat. See the Anemic Domain Model anti-pattern. The Controller only needs to know what Model to instantiate, passes the request inputs to that Model, and then injects the Model into the View script and renders. Keep in mind that a Domain Model is not a data-access class.
You can also write View Helpers to encapsulate a generic rendering of a Domain Model object, so you can re-use it in multiple View scripts.
Your View should accesses the Domain Model only in a read-only manner. View scripts should not try to effect changes to the Domain Model.
You can also design your Domain Model to implement ArrayObject or other SPL type(s), as needed to make OO usage easy in the View script.
It's true, a large driving motivation of MVC and OO design in general is decoupling. We want to allow each layer to remain unchanged as the other layer(s) are modified. Only through their public APIs do the layers interact.
The ViewModel is one solution to abstract the Model so that the View doesn't need to change. The one I tend to use is Domain Model, which abstracts the details of table design, etc. and supplies an API that is more focused on the business rather than the data access. So if your underlying tables change, the View doesn't have to know about it.
I would expect that if there's a change to the Domain Model, for instance it needs to supply a new type of attribute, then it's likely that your View is changing anyway, to show that new attribute in the UI.
Which technique you choose to decouple one layer from the others depends on what types of changes you expect to be most frequent, and whether these changes will be truly independent changes, or if they will require changes to multiple layers anyway.
The "standard" approach would be to completely prepare the model in the controller (e.g. fetch all teams, including users) and then send that to the View for presentation, but you are not bound by that. The data structures can be whatever you want it to be: Array, ArrayObject or custom Classes - anything you deem appropriate.
I dont use Zend framework, so this is in repsonse to the general MVC Have a look at the ViewModel pattern.
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx
I'm comming from a .Net MVC point of view but I believe the concepts will the same.
I will do all my view rendering in the controller bascially like below
model only output dataset/objects (this should contain the most code)
controller assign view and add necessary HTML and make use of models
view only contains placeholder and other presentation stuff and maybe ajax call
So my team can work on each part without interrupting each other, this also add some information security to the project i.e no one can retrieve all the working code they only communicate by variables/object spec.
I am new to MVC but I can already see its benefits and advantages. However, I have a (probably easy to answer) design question:
I have been thinking about models and debating the proper way to structure them. The way I see it there are a few options:
1) Models and table structure have a 1 to 1 relationship...meaning that pretty much for every table there is a corresponding model. The model class has attributes corresponding to the table columns and has whatever methods that are needed (like getters and setters) to manipulate data in the table in whatever way is necessary. This seems like the generic option and I guess I would then have the controller call the models as necessary to perform whatever business function is necessary.
2) Models are tied more closely to the operation of the business logic rather than the data: so for example if on the front end a deletion of a certain object affects multiple tables, the model then 'models' this behavior and interacts with several tables and performs the necessary function. The controller then simply needs to call a single model for whatever business behavior is desired. This is less generic since the models are much more tightly coupled..but seems quicker to implement.
3) Something in between the first 2 options. Or maybe I am completely missing the point.
Hopefully this makes sense! If I am not totally missing the point, I am inclined to think that option (1) is better. Any idea?
Edit: Not that it should matter, but I plan on using Codeigniter PHP MVC framework.
Both are valid implementations, and, depending on your needs, can work well.
Your #1 is essentially describing the Active Record pattern, which is used by SubSonic, Castle, and lots of other ORM implementations.
Your #2 is essentially describing the Entity Framework/Hibernate/LightSpeed approach, where you are dealing with objects that are more conceptually related to your domain rather than to tables. Instead of your objects containing foreign key ID properties, they actually contain the other domain object references, which are then instantiated in an on-access basis.
Both ways are great. The Active Record approach is usually more intuitive for beginners and has potentially less pitfalls. EF-style can save a lot of base-level coding and dealing with FK's directly in code.
Edit: To be clear, what you describe in both situations is data access layer related, rather then strictly model related. However in reality you're pretty close, as most models tend to simply represent one or more of these types of objects.
All of the above.
The approach you use depends on your design philosophy. If you prefer to design your application using business domains and drive that into the database design, then you favor the second approach. If you prefer to build your database first, and then create model classes from the database schema, then you favor the first approach. Both methods are valid ways to build software.
Number 1 is the way to go. Option 2 is really the controller's job. For example, the controller then takes the models and performs actions on them, and passes the results to the view.
Think of it this way:
Model = your data
Controller = business logic
View = display of data and actions
This is highly simplistic, but it's how I picture it in my mind when I go to design a system.
Think of the database as the Model, the business logic as the Controller, and the UI as the View. That may help. It's an overly simplified approach to things, but it gets the data / behavior separation roughly correct.
I don't think it has to be an either/or situation. Your first point is what would be called a Model, but your 2nd point sounds like a View Model, which is most often a composition of various Models and parts of Models that will be sent to the view. The controller is responsible for doing that composition and potentially decomposition when information is sent back from the View.
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.