Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC, 1 model 1 tables or 1 model several tables?

In MVC, 1 model 1 tables or 1 model several tables?

I am building an application that contain 3 tables. I don't know whether I should create one model for all 3 tables or create 3 models for 3 tables.

In the case I use 3 models for 3 tables, where should I put the code if I want to join these 3 tables? Put the code in any one of 3 models?

Any suggestions?

like image 902
Billy Avatar asked Jun 21 '09 09:06

Billy


2 Answers

In general, the 'Model' part of MVC should be interpreted as a 'Presentation Model' or 'View Model' - that is, a class that encapsulates all the data and behavior needed by the View. This may or may not be equivalent to the Domain Model.

Domain Models should be designed to be independent of UI. This means that such Models should not be polluted with UI-specific data and behavior - such as determining whether a particular button is enabled or not.

You may also want to show the same Domain Objects in several different views (e.g. Master/Detail, or Display/Edit), and if those views differ sufficiently, having a View Model for each View will be beneficial.

So, in general, you should design your Domain Layer and your Presentation Layer independently.

In the Domain Layer, you can choose to model your three tables as three classes. Books like Fowler's Patterns of Enterprise Application Architecture and Evans's Domain-Driven Design contains lots of guidance on how to model relational data as Domain Models.

When it comes to modeling the views in MVC, it makes most sense to create one Model per View. Such a View Model might simply encapsulate a single Domain Object, but it may also encapsulate and aggregate several different Domain Objects.

In this way, you can ensure separation of concerns, and that your classes follow the Single Responsibility Principle.

For very simple scenarios, it may make sense to collapse the Domain Model and the Presentation Model into one layer, but you should realize that this essentially means that there's no Domain Model in the solution - all models would be pure Presentation Models.

like image 112
Mark Seemann Avatar answered Nov 19 '22 23:11

Mark Seemann


Usually you will create one model per table, so in your case it means you need 3 models. When i say "Model" i mean a class that will represent a single row (usually) in a single table.

for example: Tables:

  1. Products
  2. Orders
  3. Customers

in such case the most easy and simple is to create 3 different classes (which represents the data model of the application) where the first class represents a single product the next represents an order and the last class will represent a single customer.

like image 4
yosig81 Avatar answered Nov 19 '22 22:11

yosig81