Does business logic live in the Model or in the Controller? - model-view-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!

Related

Business-Logic refers to Controller or Model. Please elaborate [duplicate]

This question already has answers here:
Business logic in MVC [closed]
(10 answers)
Closed 3 years ago.
I am confused about what is business logic. I assume that it is written in Controller but then I search it on internet but i found that many person say that it refers to model. I am highly confused. And somee community meembers give me suggestions that my question is same but you are doing mistake. I am confused by the answers in those questions. Someone says model is business logic but I assume that Controller is business logic. So Please understand my doubt.
The controller will be clean and more readable, then your all controller functions will be pure actions.
You can decompose business logic as much as you need within the model(service). Code reusability is better and there is no impact on models and repositories.
Business logic might be used in one or more places, so the model is a good place to written code.
Let's take an example:
First controller:
var getBusinessLogic = utilService.getBusinessLogic();
Second Controller
var getBusinessLogic = utilService.getBusinessLogic();
Module(Service)
this.getBusinessLogic = function () {
// return businessLogic
}
In the general sense, business logic relates to logic in an application that is determined by the application owner.
Common logic found across many different applications that is necessary for the functioning of an application is not considered business logic. This could include e.g. Create-Read-Update-Delete of entities, network calls, authentication etc.
Business logic is logic that is unique to the owners of a specific application.
As such, business logic can show up in any part of an applications code.
However, some people would argue for e.g. 'thin controllers' and 'thick models'. A thin controller is one which contains little to no business logic and defers heavily to the model for performing the appropriate business logic e.g. during Create, Read, Update, or Delete operations.
In an angular sense it is similar, angular controllers are primarily responsible for preparing model data for the scope, the same way an API controller is responsible for preparing data for API requests, and you could aim to minimise the business logic in controllers.
However, business logic doesn't always fit brilliantly in Models either - what if it the update of one model requires updates to other models? This is why often Model Controller frameworks will provide another option - Services. Services provide a more abstract place to perform business logic that is e.g. not related to a single model.
Overall, one good option is to try to keep your controllers 'thin' and keep business logic in models and/or services.

Should I save related models in repository?

I am working with Laravel for almost two years and trying to understand all the benefits of using Repositories and DDD. I still struggle with how to use best practices for working with data and models for better code reusability and nicer Architecture.
I have seen other developers suggesting to generate models in factories and then use Repositories for saving these models like :
public function add(User $user)
{
return $user->save();
}
but what should I do, in case my user model has models related with it, like images, description and settings.
Should I create repository for each model and call ->add() function 4 times in the controller or should I place the saving logic inside the UserRepository ->add() function passing all models as well as user? Also, how about update function, that logic might also be quite complicated.
Update - what I need is a practical example with realization.
It's always difficult to deal with "right way" questions. But here is one way.
From a DDD perspective, in this specific context, treat the User object as an aggregate root entity and the other objects as child value objects.
$description = new UserDescripton('Some description');
$image1 = new UserImage('head_shot','headshot.jpg');
$image2 = new UserImage('full_body','fullbody.jpg');
$user = new User('The Name',$description,[$image1,$image2]);
$userRepository->persist($user);
First thing to note is that you if really want to try and apply some of the ddd concepts then it is important to think in terms of domain models without worrying about how to persist them. If you find that you are basically writing a CRUD app with a bunch of getters and setters and almost no business logic then pretty much forget about it. All you will end up doing is to add complexity without much value.
The persist line is where the user will get stored. And you certainly don't want to have to write a bunch of code to store and update the children. Likewise, it would normally be waste of effort to make repositories for value objects. If you are going this route then you really need some sort of database layer that understands individual objects as well as their relations. It is the relations that are the key.
I assume you are using Laravel's Eloquent active record persistence layer. I'm not familiar enough with it to know how easy it is to persist and update an aggregate root.
The code I showed is actually based more on Doctrine 2 Object Relation Mapper and pretty much works out of the box. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/ It is easy enough to integrate it with Laravel.
But even Doctrine 2 is largely CRUD oriented. In different domain contexts, the user object will be treated differently. It can start to get a bit involved to basically have different user implementations for different contexts. So make sure that the payoff in the domain layer is worth the effort.
I am not a PHP guy but from what I can find, Laravel an MVC framework, which has nothing to do with DDD.
Check this presentation, it does not to go to domain modelling, more concentrating on tactics but at least it has some goodness like command handling and domain events, briefly explains repositories with active record.
It also has references to two iconic DDD books at the last slide, I suggest you have a look at those too.

MVC - which methods should be in Model class except set/get members?

Should methods that manipulate the Model class members be implemented in the Model or in the Controller? Does it depend on how "heavy" this manipulation is ?
By "manipulation" I mean:
get a class member
make a long calculation based upon this class member
return another value which relates to this class
For example, a Board class which hold a cell matrix member.
Now I want to implement a method which returns all the surrounding cells according to specific cell location.
Is the model or view responsible to for implementing the above ?
If this question belongs to another Stack Exchange QA site I will welcome the recommendation to move my post to that site.
Keep your controllers thin, don't let them do much, this aligns with the Single Responsibility Principle in SOLID for Object Oriented Design. If you have fat controllers, they become hard to test and maintain.
As for the models, I used to have dumb models before that did nothing but to map to database tables and that was inspired by most of the sample applications that you see on the web, but now I don't do that.
I (try to) follow the principles from Domain Driven Design, where models (entities in DDD terms) are at the center of the application, they are expected to encapsulate behaviour related to the entity, they are smart models (so yes, the logic related to an object will live with it in that case). DDD is a much bigger topic and it is not related directly to MVC, but the principles behind it helps you better design your applications, there is a lot of materials and sample apps available if you google DDD.
Additionally, Ruby On Rails community - which seems to inspire most of MVC frameworks - also seems to have a hype around having Fat Models and Skinny Controllers.
On top of that, you can add View Models to your mix which I find helpful. In this case, you can have a ViewModel to represent a dumb subset of your model(s) just to use for generating the view, it makes your life easier and further separate your Views from your Models so that they don't affect your design decisions unnecessarily.
What you call "model" is are actually domain objects. The actual model in MVC is just a layer, not concrete thing.
In your particular example, the Board should have a method that returns this list. I assume, that you are actually acquiring it because you then need to do further interaction with those cells.
This is where the services within the model layer comes in to play. If you use them, they are the outer part of model layer and contain the application logic - interaction between different domain objects and the interaction between the persistence (usually either data mappers or units of work) and domain objects.
Let's say you are making a game, and you and player performs and AoE attack. Controller takes a hold of service, which is responsible for this functionality and sends a command: this player aimed AoE in this direction, perform it.
Service instantiates Board and asks for surrounding cells of the target location. Then it performs "damage" on every cell in the collection that it acquired. After the logic is done, it tell the Unit of Work instance to commit all the changes, that happened on the Board.
Controller does not care about the details of what service does. And it should not receive any feedback. When execution gets to the view, it request from model layer the latest changes and modifies the UI. As the added benefit - services let you stop the business logic from leaking in the presentation layer (mostly made up from views an controllers).
The domain object should contain only methods, that deal with their state.
I think this has little to do with MVC, and a lot more to do with regular software engineering.
I personally wouldn't hesitate to stick trivial calculations in a model, but would be extremely wary of fat models.
Now, the fact that MVC stands for Model View Controller doesn't necessarily mean that everything should be either a view, a model or a controller. If you feel the need to move responsibilities to a separate class that doesn't really qualify as an M, a V or a C, I don't see why you shouldn't do it.
The way you implement it is up to you. You could either use this separate class as a "top level" (for lack of a better term) object, or make a method of the model delegate to it, so as to hide the fact that you're using it. I would probably go for the latter.
Everything is debatable, though. Everybody and their sister seem to have a different opinion on how to do MVC right.
Me, I just consider it a guideline. Sure, it's a great idea because it leads you to a better separation of concern, but in the end—as it always happens—there's no one-size-fits-all way to apply it, and you should not be overly constrained by it, to the point where everything has to be either a view, a model or a controller.
As per best practice we should use properties for Calculated fields with get access only. example public double TotalCost {
get
{
return this.Role.Cost * TotalHour;
}
}

What exactly is the model in MVC

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.

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