How should I make a Class Diagram in MVC? - model-view-controller

Here's my classdiagram:
In my perspective (since each cannot function without the next one):
models compose the repositories,
repositories compose the services,
the services compose the controllers.
I think I'm wrong in my understanding of UML relationships.
What is the right way to make a class diagram in MVC?

Terminology and semantics
If classes cannot function without another one, there is a dependency. A dependency does absolutely not imply composition.
In object oriented programming, we often refer to composition, in the sense object composition. This relationship is stronger than a simple dependency. It means that each object of the class may need to knwow objects of the other class. In UML we represent this with an UML association.
In some case, the links between objects are stronger, and may have UML aggregation or UML composition semantics. But it's not because you compose objects, that there is an UML composition. Same term, different meaning (some more advice on using UML association and composition and avoiding UML aggregation: here).
In MVC, the Controller is associated with the Views and the Model, and each Views is associated with the Model as well. There is no UML composition.
Notation
You cannot compose a class with a package. Packages describe namespaces and can be nested. They can contain other UML elements. But they cannot be associated/aggregated/composed with classes.
What you are looking for seems to be a component diagram: components can be nested, and be relate to other components via interfaces. And a component can contain classes.
Content of your diagram
There seem to be a slight confusion between the DDD domain model and the MVC model. Despite the same term, the two concepts are different.
In MVC, the Model manages the knowledge, meaning the domain model and everything needed to cope with the domain model:
User, Transfer and Tax are DDD domain entities/aggregates and belong to the MVC model
Everything needed to persist this knowledge, such as UserRepository, TransferRepository, TaxRepository also belongs to the MVC model. If you'd use another persistance approache (e.g. table gateways, or active objects) you would not have repositories but other objects.
The MVC Controller processes the user input, and sends commands to views and the model. It is not a repetition of the domain objects.
Where are the views ? What is the purpose of your services ?
are they domain service, i.e. operation that involve several aggregates and do not naturally belong to any single one of them ?
are they a service layer of an application, meant to link it with the outside world?

Related

MVC pattern in model with multiple classes

When applying the MVC pattern to a design with multiple classes do I need to create a model, view and controller for each of the relevant classes?
For example, for a design with a domain with UserAccount class, a MultimediaContent class, etc, would I need to design a UserAccountModel, UserAccountView, UserAccountController, and a MultimediaContentModel, MultimediaContentView, MultimediaContentController, etc?
I've looked for examples online but they all use a single class.
In the he original MVC as decribed by its inventor a:
an application should have one controller
a controller can provide input and commands to several views,
an applications can manage multiple models.
This is is a very high level description because each of these main "components" could be made of multiple classes. So it is fully up to you to decide of the best mapping.
Other principles, such as the separation of concerns, would suggest to have different views for different model objects. So a UserAccount, and a UserAccountView is in general a sound approach. But you could still have combo views that refer to serveral different model objects at once.
You will find many more flavors of MVC regarding the controller. The single controller monopolizing the user input and controlling all the views and commanding the domains, is no longer a reality, since many windowing system attach the controller to a window. So you'd probably have a swarm of controller, with an AppController and an additional controller for each view, e.g. UserAccountViewController, rather than a controller per domain object.
Of course, in a very simple application, with a few relatively independent domain object, each having a single view, you could find the objects as you describe them.

Does a Model in MVC Need To Be a Class Or is That Just a Common Pattern?

I realize I'm conflating / confusing two different topics, but it seems like in most popular MVC frameworks that I've come across the model is a class / object-oriented (and uses some sort of ORM or ODM that I might not want to use).
My question is: If I split my files into models, views, and controllers, but my model is simply a separate file that handles business logic, validates data and handles communication with a database... but I do it in my own way that isn't object-oriented... and maybe just uses super simplistic if statements for validation... is that still considered a model? Would that still be considered MVC?
Does the model need to be a class / object-oriented or is that just a super common pattern / preference?
Thanks!!
In general "Model" refers to your Business Object Model (BOM). If you subscribe to Domain Driven Design (DDD) then your Models in a Model View Controller (MVC) architecture will be representative of your BOMs as classes or interfaces. Those BOMs may also be your classes in an Object Relational Map architecture. Since it is better for an interface to be a description of what something can do and a class as a description of what something is, you would tend to see your Models represented as classes rather than interfaces. In terms of what "logic" is allowed inside of those model classes it is really up to you and your team. For example, while it is typical to put data validation in Models you may want to abstract those rules to a separate data validation class that your model uses. There is typically not a black and white rule about where business logic goes but it is generally considered best practice for each class to have a single responsibility based on the Single Responsibility Principle as part of the SOLID model. From my experience when I have called "Model" classes things that were not the Business Object Models, like a "RepositoryModel", it can be confusing about where the code representation of the data model was. Instead I recommend using the word "Model" to be reserved for things which end users are familiar with and avoid the word "Model" for things they cannot.

Differentiating between domain, model, and entity with respect to MVC

Can someone explain these 3 concepts and the differences between them with respect to an MVC framework along with an example. To me these appear almost equivalent, and it seems they are used interchangeably in some articles and not in others.
The terms are a bit vague I agree. I would use domain to refer to the business area you are dealing with. Like banking or insurance or what not. Then you have domain models. These are the things you deal with in that business domain, like for domain of banking you have accounts, customers, transfers etc. I would use term entity for referencing the class/POJO or the persisted / concrete version of a model.
What probably confuses you here is that in the term MVC, the model is a concrete thing, but it references the data model used to represent some presentation in a web GUI so don't get that mixed in with the above explanation.
The terms you are confused about are: "domain objects", "domain entities" and "model objects". While usually used interchangeably, the domain entities and model object can also be instances of active record pattern (basically: domain objects with added storage logic).
In ordinary domain object there is no storage logic. It gets handled by data mappers.
The term "model objects" comes from Fowler's books (read PoEAA for more details), and, IMHO, is part of the confusions MVC, because the entire model is an application layer (MVC consists of it and presentation layer), which contains those "model objects", which are usually dealt with by services (in that image, the model layer is all three concentric circles together).
I much prefer to use "domain object" term instead.
The term "domain entity" (or "entity object") is usually used when author implies that the object is a direct representation of a storage structure (more often - a database table). These are also almost always implementations of active record.
P.S.: in some articles you would also see term "models" (plural). It usually is not directly related to MVC design pattern, because it talks about Rails-like architecture, where "models" are just active records, that get directly exposed-to/created-by controller.
.. not sure whether this confused you more
For the record. In practical purpose, domain and model are the same, while entity is also a domain/object that would be used to store in the database.
Some people are tried to re-explain such topics but none of them are canon.
The difference is that, in the world of Java, Domain is more used, while in the world of C#, Model is used (and MS encourages his use) but its just convention and you can use both.
In the same, concept, Value Object (VO) is used by the people of Java, while DTO for the people of C# even when both are practically the same. Also POJO (Java) vs POCO (C#), Packages (Java) vs NameSpace (C#), Setter and Getter (Java) vs Encapsulation (C#)
Both domains and models are classes. How the class is use distinguishes if it should be classified and put in a domain or model folder. If the class is going to be used ONLY in the view, put it in the model folder. If the class is mapped to a database object, then put it in the domain folder.

How can I attach UI layer resource files to domain model data annotations?

This question really has larger architectural implications and I welcome any input or suggestions on this:
I'm more of the Martin Fowler school of thought when it comes to OOP. I believe you should be able to directly render domain entities in the UI. If I have a Car entity, I should be able to render it to a webpage. The domain model is a crosscutting concern and not a layer. Treating the domain model as a layer leads to an anemic domain model. I don't believe in DTOs in an OOP architecture.
A view model for me is a way of composing the domain entities required in your view. It's not a DTO. I don't understand what the reasoning behind using a view model like DTO is though it seems like a common thing to do using automapper?
So using the metadata approach I put data annotations on my domain model to give any UI implementation hints on how to render and validate the entities. I like to have a richER domain model.
In MVC3 how can you accomplish this (specifically using the Display data annotation) with a resource file that resides in the UI layer? Is there a native implementation for this or do I need to get creative myself? Or have I gone wrong somewhere in my approach?
I disagree.
For one thing, some of the attributes you will use to specify how an entity property should be displayed on a web page come from the System.Web namespace, not the System.ComponentModel.DataAnnotations namespace. By putting these attributes on properties in your domain model, your domain model is taking a dependency on System.Web. For example, there is the [HiddenInput] attribute that tells MVC3 to render a field as input type="hidden". This is not in System.CompoenentModel.DataAnnotations.
Secondly, I don't believe you need data annotation attributes on your entity properties to have a rich domain model. A rich domain model comes from classes that wrap knowledge in a context. The client application should not need to know anything about the domain in order to use it. You achieve a rich domain model with classes, methods, and properties that describe knowledge using the ubiquitous language. DataAnnotations attributes don't lend themselves well to the ubiquitous language imo. And, your domain is more than just your entities. There are factories, services, and other patterns that you can use to build a rich domain model. A domain with only entities and metadata sounds anemic to me.
Thirdly, you may have an entity that should be rendered in different ways on your web site. When someone searches for a car, you may want to display just the make, model, year, and thumbnail photo. When someone clicks on the search result, you may want to display multiple photos, reviews, etc. If you were to use the UIHint attribute on an entity to tell the web ui how to render the car, you wouldn't be able to have different strategies for rendering the Car in different contexts.
Finally, yes, automapper is really great for DTOing your entities into viewmodels. It essentially lets you populate copies of the entity, disconnected from the domain, targeted for specific UI concerns. Here it is safe to use HiddenInput and UIHint attributes to tell MVC3 how to render data.
Response to comment 1
As far as UIHint, I mentioned it here because it has a special meaning with MVC3 EditorTemplates. In cases where a partial view involves receiving input, what is the composition of the view? Text fields, drop-down lists, and input elements that often correspond to entities and their properties in some aggregate root. You will therefore need some representation of the entities to encapsulate the data. Your DTO can be an aggregate root as well, with depth. You can have a root DTO with scalar properties (text/date/bool), navigation properties (drop-down list) and collection properties (ul/ol/table).
We create a corresponding viewmodels for many entities in an aggregate root, and implement them as views using EditorTemplates. If we ever want to switch to a different EditorTemplate, we can apply UIHint to a viewmodel property. Thus we can tell it to "render a location dto as a google map". Automapper can map navigational and collection properties to corresponding viewmodels, forming as complex a representation of your domain entities as you need for the user.
Forgive me if I misunderstand what you mean by flat dto.
Response to comment 2
A viewmodel dto can flatten out / denormalize some properties (using automapper), if your requirements call for it. For example, consider a University entity. It may have many names in many languages (translations), hinting at a UniversityName entity in the aggregate, with University having a collection of Names (1..n). Of those names, 1 may represent the OfficialName / NativeName, and another may represent the TranslatedName to the user's CurrentUICulture. Other entities in the collection may represent TranslatedNames that the user does not understand, and need not be bothered with.
If you have a view that is only interested in these 2 Names in the collection, you can promote them to first-class properties on the viewmodel:
public class UniversityViewModel
{
public string OfficialName { get; set; }
public string TranslatedName { get; set; }
// ...other properties
}
This is a case where denormalizing part of the entity when converting to a viewmodel dto can make sense. Notice how the viewmodel is anemic -- a bare container for data transfer from a controller to a view. This is perfectly fine, and in fact, encouraged.
Answer to original question
To answer your original question, it helps if you think of your domain model & entities as a layer -- more specifically, a bottom layer. Layered software is easier to understand if you think about the various concerns in an application as having dependencies on other concerns. MVC3 is a presentation / UI layer, and will have dependencies on the layers beneath it -- one of those being your domain layer.
If you want to access a resource file in the UI from the domain layer, you are going in the opposite direction. You would be making a low layer depend on a higher layer. If your domain lib depends on the UI lib for a resource, and the UI lib depends on the domain for entities, you end up with a circular dependency. I think you could probably accomplish it using reflection if you needed to, but in that case, you would be fighting against the framework. MVC and .NET in general may not be the best choice for you if that is the case.
I actually think of resource files as a cross-cutting concern. Our application has i18n sprinkled throughout, and often we find we need the same language text resources in both the domain and the UI.
There is nothing wrong with putting a Display attribute on an entity. But if you want to use resources for it, then either put that resource in the domain layer, or if you feel it doesn't belong there, in a lower layer. That way it can be accessed by both the domain and the UI.
So I ended up putting a resourse file in the domain model and added a custom HiddenFieldAttribute so that I don't have to reference the MVC assembly in the domain model.
I still fundamentally dissagree that a view model is really a DTO and that the domain model should be constructed as a layer. I feel that architecting the application in this way creates abstractions that really have no value. If the domain model was truly a layer then we would build a set of logical interfaces from which to access it, and this we don't do. It's a cross cutting concern.
Thanks to olivehour for an interesting discussion and suggesting that it's okay to place resource file(s) in to domain model assembly.

MVC coupling between models

Can a model depend on another model? Say I have a log model that other models want to access.
If it's between models that model the same part of the domain but are intended for different purposes (you mentioned logging, others would be reporting) there should be as little coupling as possible. Not to say that there should be none.
If the models model different parts of the domain coupling should be fine. If you notice your models are overlapping you should refine your context-/model- boundaries.

Resources