What exactly is the model in MVC - model-view-controller

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.

Related

Does business logic live in the Model or in the Controller?

After reading https://softwareengineering.stackexchange.com/questions/165444/where-to-put-business-logic-in-mvc-design/165446#165446, I am still confused as to where I want to put my code for computing discounts. Computing a discounted price for a product or service I think is definitely part of business logic and is not part of application routing or database interaction. With that, I am struggling where to place my business logic.
Example
class Model
{
public function saveService($options)
{
$serviceId = $options['service_id'];
//Model reads "line Item" from database
$service = $this->entityManager->find('Entity\ServiceLineItem', $serviceId);
//uses the data to compute discount
//but wait.. shouldn't model do CRUD only?
//shouldn't this computation be in Controller?
$discount = ($service->getUnitPrice() * 0.25);
// Add the line item
$item = new SalesItem();
$item->setDiscount($discount);
}
}
class Controller
{
function save()
{
$this->model->saveService($options);
}
}
Question:
Above $discount computation, should it stay in Model, or does it go into Controller? If it goes into Controller, Controller has to call $service (via Model) first, then compute $discount inside Controller then send it the value back to the Model to be saved. Is that the way to do it?
Note
I may be confusing Model with "Storage". I probably need to have a Model where I do business logic and Database/Persistent Storage should be a separate layer.
Business logic belongs in a Service, so you would need to add a service layer.
Business logic tends to span multiple models, which infers that it does not belong in any single model. Therefore, it is unclear in which model you should put the logic.
Enter the service class.
I tend to make a service for each use-case the software is designed for.
In your case there could be a CheckOutService which would calculate your total sum, including discounts.
That way each service has a specific and intuitive purpose. Then, when a controller requires some business logic, it calls a service tailored for that very purpose.
A good description of what a service does in the MVC pattern can be found here:
MVCS - Model View Controller Service
I'll quote the most essential part:
The service layer would then be responsible for:
Retreiving and creating your 'Model' from various data sources (or data access objects).
Updating values across various repositories/resources.
Performing application specific logic and manipulations, etc.
edit: I just saw kayess answer. I'd say his answer is more precise than mine, but I don't know how relatable it is, given the degree of uncertainty in your question. So I hope mine can help some people in the earlier stages of their programming career.
Answering a question like this is usually opinionated or one could say it really depends on your business use case.
First off, i sense some mixup in your Model and service wording here.
A model should be your domain model, and service should either be a domain or an application service, in a different class or a different layer.
Architecturally thinking you could follow a rather simplified DDD-ish implementation.
Namely:
You implement all behavioural concepts in your domain model, which are related to the models current state
Use a factory that will query the line item from the repository
Use a domain service for mostly everything that's not related to your model, in your case calculating discount (if you need that logic reusable, for example in more models or services). You don't want to pollute your domain model with non related mechanisms and dependencies
For persistence you better use a different layer and by this you better separate most concerns you can, a reason for this is testability and another reason -amongst many others- for less code changes later
To achieve a cleaner architecture and less pain by maintaing your code in the longer run, don't forget to think about how design patterns and SOLID principles could help you implement your solution to the given business use case.
The question about how to separate business logic from data is not easily answered. However, Daniel Rocco has constructed a good discussion of the subject that you may find helpful, if not for this particular problem, then for structuring business applications in general.
I used a framework called "Yii Framework" using MVC, what it had was a function called beforeSave() in the controllers that was used to change the model values just before saving them.
Following this logic maybe the best practice would be to apply the discount to your price just before saving the model (in your Controller)
The Below Image shows how I think where your "Business" logic should go :)
The above image has the "Service" layer as the Server Side "Controller".
It is the middle man between the "Client" side Controller and the "Logic" layer.
All of your tasks that requires some type of "Logic" like
"Computing a discounted price for a product or service"
Would go into a ProductLogic Class where it takes inputs From the Service if needed and uses that information to help calculate the discounted price.
The ProductLogic Class will also query a "Data" source if needed to get the current price of an item.
The ProductLogic Class will piece together the information it collected from the Service and Repository to make the calculation and if it needs to be return to the user then the ProductLogic class will send it to the Service layer.
If it just needs to be saved in the Repository than the Logic will pass off the information to the Repository to handle.
Hope this helps :)
Have a great day!

In a MVC application, should the controller or the model handle data access? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
We are having some philosopical debates in our company about where the calls to the Business Logic should be to perform CRUD operations.
I believe that the Model should consist of your data structure and that the controller should be responsible for populating the data.
My co-worker believes that all population should be done in the model class itself, and simply called by the controller. This keeps the controller neat and clean (but, in my opinion, clutters up the model).
He also believes that any call that returns a Json object should happen in the model, not in the controller. The model would return an array to the controller, which would then return this as a Json object.
What are some different pros/cons to each and is there a right or wrong way to do this?
All business logic should be in the MODEL.
Remember, the responsibilities of each layer are thus:
Controller - bridge between the model and view. Decides where to go next.
View - displays the data, gathers user input
Model - business logic, interface to data store.
One of the biggest gains is in maintenance and (later) expansion. In general:
If you need to change business logic, you should not need to modify your controller or view.
If you change your visual display, you should not need to modify your model or controller.
If you change your workflow, you should not need to modify your view or model.
To do the above, each layer should have no knowledge of the others in order to work properly. For example, the view should receive its data and not need to know anything about where it comes from in order to display it properly. The controller should not need to know anything about the underlying structure of the model in order to interact with it. The model should have no knowledge of how the data is to be displayed (e.g., formatting) or the workflow.
"He also believes that any call that returns a Json object should happen in the model, not in the controller. The model would return an array to the controller, which would then return this as a Json object."
NO. The Model should never format data. It also should not read formatted data. That is polluting the model and moving into the level of hell where business logic = display logic.
JSON (coming in or going out) is just another view. So going out:
Data Store -> Model -> Controller -> View
Coming in:
View -> Controller -> Model -> Data Store
FYI, my primary language is PHP, so you can take this all with grain of salt.
The business business logic in MVC and MVC-inspired patterns has to be in the model layer. And yes, model is supposed to be a layer, not a class or object.
Most of said logic would reside in the domain objects, but some of it would end up in services, which should at like "top-level" structures in model layer, through which presentation layer (views and controller) interact with model layer.
Services also should facilitate the interaction between storage abstractions (data mappers, data access objects, units of work and/or repositories) and the domain objects. These structures would deal with persistent and temporary storage and deal with data integrity.
This sort of separation simplifies both the maintenance and testing of the codebase. You gain the ability to easily test you domain logic, without ever touching database (or any other form of storage.
Controllers (and the equivalent structures from other MVVM and MVP patterns) should be extracting information from user's request and changing the state of model layer (by working with services) and the view.
If you implement MVP or MVVM, then the controller-like components would have additional responsibilities, including data transfer from model layer to view, but in classical and Model2 MVC patterns the view is supposed to be an active structure, which request data from the model layer.
As for generation of JSON, that actually should happen in the view. Views are supposed to contain all (or most, depending on how you use templates) the presentation logic. It should acquire information from model layer (either directly or though intermediaries) and, based on that information, generate a response (sometimes creating it from multiple templates). JSON would be just a different format of response.
There has be huge impact (and mostly - negative) by Rails framework, which was released in 2005th. The original purpose of it was to be a framework for prototyping - to quickly create a throw-away code. To accomplish this they simplified the pattern to the point where the separation of concerns was broken.
They replaced model layer with collection of active record structures, which easy to generate and merged the view functionality in the controller, leaving templates to act as replacement for full blown view. It was perfect solution for initial goal, but, when it started to spread in other areas, introduced large number of misconceptions about MVC and MVC-inspired design patterns, like "view is just a template" and "model is ORM".
Your controller methods should be as thin as possible, which means that data access belongs in the model (or more specifically, a Repository object).
Think of your controller methods as a switch-yard... they are only responsible for delegating tasks to other methods for execution.
If you are writing any Linq code in your controllers, you are creating a dependency that will have to be modified if your site structure changes, and you are potentially duplicating data access code. But GetCustomer in the model is still GetCustomer, no matter where you're calling it from your Controllers. Does that make sense?
Business logic that is more extensive than simply accessing data can be put into its own Business Logic Layer, which is considered part of the Model.
I'm not so sure about the JSON. JSON is just an alternative data representation; if you have a utility method that can transform your data classes to JSON, call GetCustomer from the Model, and perform the transformation to JSON in your controller method.
The Model should handle data access.
From MSDN:
Models. Model objects are the parts of the application that implement
the logic for the application's data domain. Often, model objects
retrieve and store model state in a database. For example, a Product
object might retrieve information from a database, operate on it, and
then write updated information back to a Products table in a SQL
Server database.
In MVC, the model is responsible for handling data access. The pro is that all data access code is encapsulated logically by the model. If you included data access code in the controller you would be bloating the controller and breaking the MVC pattern.

What is the "model" in the MVC pattern?

So I did some Google searching on the MVC pattern and I'm still not exactly sure what the "Model" part is. What exactly does it deal with? I'm rather new to programming so all the explanations I can find go right over my head. I'd really appreciate it if you could give me an explanation in simple terms.
Thanks
The simplest way I can describe it is to call it the "Data" part. If it has to deal with getting or saving data, it's in the model. If you have a web application, the model is usually where you interact with a database or a filesystem.
Model in MVC is a place where data presented by the UI is located. Therefore, it shouldn't be confused with Domain Model which serves as a skeleton that holds the business logic.
Certainly, for a small application that serves as a service for CRUD operations backed by a database these two models can be the same. In a real world application they should be cleanly separated.
Controller is the one who talks to the application services and the Domain Model. It receives updates back from application services updating the Model which is then rendered by the View.
View renders the state hold by the Model, interprets User's input and it redirects it to the Controller. Controller then decides if the Model is going to be updated immediately or first the information is forwarded to application services.
The Model can represent your "Domain Model" in smaller projects. The Domain Model consists of classes which represent the real-world entities of the problem you're dealing with.
In larger projects, the Domain Model should be separated out of the actual MVC application, and given it's own project/assembly. In these larger projects, reserve the "Model" (i.e. the "Models folder in the MVC project") for UI presentation objects (DTOs - Data Transfer Objects)
The model is respomnsible for managing the data in the application. This might include stuff like database queries and file IO.
the view is obviously the template, with controller being the business logic.
The model is used to represent the data you are working with. The controller controls the data flow and actions that can be taken with the data. The view(s) visualize the data and the actions that can be requested of the controller.
Simple example:
A car is a model, it has properties that represent a car (wheels, engine, etc).
The controller defines the actions that can be taken on the car: view, edit, create, or even actions like buy and sell.
The controller passes the data to a view which both displays the data and sometimes lets the user take action on that data. However, the requested action is actually handled by the controller.

why model view controller is not view logic database?

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.

Zend Framework / MVC: What type of objects to push to the View?

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.

Resources