Understanding MVC: Whats the concept of "Fat" on models, "Skinny" on controllers?
Asked Answered
P

5

22

I'm trying to understand the concept of "Fat" on models vs "skinny" on controllers and from what I've been discussing I have the following example (this is taken from a freenode discussion):

Q: On MVC paradigm, its said Fat models, skinny controllers. I'm here thinking, If I have lots of methods (on controller) that uses just a few abstract methods to CRUD (on model), am I creating a fat controller instead of a model ? Or they say, fat model, refearing in what is returned and not typed ? that's something I've never understood =) Any comments are appreciated! Thanks a lot

OBS1: I'm not doing whats ment by the model, in the controller, I just have methods that control whats going to the model

OBS2: let's say "checkIfEmailExists()", has "[email protected]", as a parameters. This method will, get the return from the model method that querys if this param exist in table, return boolean. If is 0, "checkIFemailExists()" will call a diferent model method, this one, he's just another abstract method, that performs Update operation.

OBS3: The "checkIfEmailExists()", isnt just a controller ? He's not actually performing any CRUD, he's just comparing values etc. That's whats confusing me, because in my head this is a controller :S

Notes: I guess this is not the best example, since saying "check if something exists",sounds like a query my table operation

Q2:just one more question, so, let's say I've got a view form, from where that email address parameter is sent from. Are you saying the view goes directly to the model ?

Q3:Shouldn't the controller act between them ? thats the paradigm

FINAL NOTE: The discussion ended, saying that I'm wrong, wish is ok (i'm learning). But, so, whats the right answers for Q2 and Q3 ?

Thanks for your atention

Passionless answered 24/6, 2010 at 12:3 Comment(1)
Just an observation: you're much more likely to get useful answers if you ask short, well-organized, to-the-point questions rather than just writing down everything that comes to your mind on the subject.Dituri
D
35

Your application is the M. It should be able to stand independent from V and C. V and C form the User Interface to your application. Whether this is a web interface or a command line interface shouldn't matter for the core business logic of your application to run. You want the model to be fat with business logic.

If you have a fat controller instead, e.g. full with business logic, you are not adhering to the purpose of MVC. A controller's sole responsibility is handling and delegating UI requests to the Model. That's why it should be skinny. It should only contain code necessary for what it's responsible for.

Simplified Example

public function fooAction()
{
    if(isset($_POST['bar'])) {
        $bar = Sanitizer::sanitize($_POST['bar']);
        $rows = $this->database->query('SELECT * from table');
        try {
            foreach($rows as $row) {
                $row->foo = $bar;
                $row->save();
            }
        } catch (Exception $e) {
            $this->render('errorPage');
            exit;
        }
        $this->render('successPage');
    } else {
        $this->render('fooPage');
    }
}

When it should be

public function fooAction()
{
    if(isset($_POST['bar'])) {
        $success = $this->tableGateway->updateFoo($_GET['bar']);
        $page    = $success ? 'successPage' : 'errorPage';
        $this->render($page);
    } else {
        $this->render('fooPage');
    }
}

because that's all the controller needs to know. It should not update the rows. It should just tell the model that someone requested this change. Updating is the responsibility of the class managing the rows. Also, the controller does not necessarily have to sanitize the value.

As for Q2 and Q3, please see my answer to Can I call a Model from the View.

Democrat answered 24/6, 2010 at 12:27 Comment(6)
Well put! Keep your business logic out of the controller.Germinal
+1 That second paragraph is gold. Thin controllers are a manifestation of adherence to the MVC architecture and the single responsibility principle.Agosto
So if I get it right, all my models will hold all the crud functionality and all my controllers will hold the "logic" (eg. form validations, user redirections etc etc)?? am i right??Concomitant
@Lykos Almost. Your model is not just the database. It's your entire application minus the User Interface. Your model will contain data access and processing logic. Form validation is an aspect of the UI but should not go into the controller directly but into dedicated Validation classes (so you can reuse them). You can use them in the controller though. Redirection is not UI but transport layer, e.g. when you use HTTP, it would fit into a Response object of some sort. The controller really is just a delegator.Democrat
Well, in my case i have recently started learning CodeIgniter, so here's an example. Suppose that i have a user that does a registration. All the crud -the insert- will be in my user_model. In order to apply some validation to the post inputs, i'd have to load the form_validation class. So here comes the point for the question I said before. Should I apply my validation (the form_validation_run() function) to my controller or push it in my user_model too?? where should i load the form_validation class? inside my model or in the controller??Concomitant
I'd say forget about "forms". It's really input validation. There is two sides to that: checking that enough data is present to delegate from C to M. And then validating that the data can be processed by M. So it's really two things. Also see #26175 and #2069127 and google.de/…Democrat
F
9

I've been working with MVC paradigm for a long time and I can share with you my experience.

The "model" part is responsible of handling all the stuff that isn't strictly "web", such as validation, logic, data access, etc. Think of it as a sort of mixed business layer + data access layer. You can also have BLL+DAL in separate assemblies and use the "Model" part of MVC as a bridge between your BLL and your App, plus adding classes that are specific to the MVC app and not related to the BLL, such as ViewData classes, etc.

The "controller" part is what takes care of the web specific stuff, like authentication, cookies, GETs and POSTs, querystrings, etc. It uses the stuff present in the model and/or the BLL and sends the data that has to be rendered to the user to the views.

The "views" are your html templates that can receive data from the controller, and display it. No logic operations should ever be done in the views, so no "if" statements, no loops, etc. If you find yourself having such needs, then you need some "helper" methods that create the desired html and then call them from the view. So views only receive data, and offer to the user links/forms to post the data to a controller, but they don't elaborate anything.

Hope this cleared some of your doubts.

Frisse answered 24/6, 2010 at 12:11 Comment(3)
This is well put, however I disagree about views, they shouldn't be absent of all logic, display logic is needed. Often in an attempt to remove all logic from views people end up creating far too many partial views, or worse then that they add "view" data (such as HTML or XML) into the controller or helper methods. A better way to look at it is you should only pass formed data to the view, no further manipulation should have to be done to it other than to display it, if displaying the data requires a loop then so be it.Expeditionary
@evolve I agree, there isn't too much wrong with putting <?php echo $message_count == 1 : 'message' : 'messages' ?> in a view to display a singular word when needed. At least if it is within a view the language has been separated from the controller.Octavia
Matteo, doesn't saying "Think of [Models] as a sort of mixed business layer + data access layer" break the Single Responsibility Principle? I wonder if the term phrase "Fat Model" is an anti-pattern.Sheeb
C
3

I've always interpreted that to mean that the models should encapsulate logic related to those models in a more object-oriented approach, as opposed to having all the logic in the controllers in a more procedural approach. To quote The Cathedral and the Bazaar:

Smart data structures and dumb code works a lot better than the other way around.

Cabral answered 24/6, 2010 at 12:16 Comment(0)
R
2

I may be showing my bias (towards C#) but I don't think it makes much sense to talk about MVC unless you're using an object-oriented programming style. A controller isn't a method, it's a collection of methods grouped into a class, each of which handles some input (url/request). A model isn't a way of accessing the database (that's a data access layer), it's a collection of properties and methods that encapsulate some identifiable entity in your application: a person, a reservation, a product, etc. The best way to think about it is that controllers handle input, models contain data -- but, of course, that's simplified.

The question of "Fat" vs "Skinny", to me, is the question of where does your business logic live. If you have lots of logic in your controller related, not to simply handling input, but implementing business logic, then your controller's are relatively fatter than if you simply use them to translate requests into assemblages of models that are handed off to a view to render. In my experience, it's not always an either/or decision. A lot of the time you have business logic (validation, relationship maintenance, auditing) in the model while you have application logic (permission validation, sanitization, etc.) in the controller, too.

Richela answered 24/6, 2010 at 12:20 Comment(3)
MVC is not necessarily bound to object oriented programming. You can also implement the idea of separating data,logic and presentation in C or any other non OOP language. Of course it wirks best in OOP :)Wildawildcat
@Techpriester - but aren't you then applying principles of OO despite the language's support (or lack thereof) for it. You may just end up with 3 big objects, but you still need to think of them that way to make sense of it.Richela
Not really. When using the MVC principle in a non OOP language you just have to make a clean separation between the three parts. The concepts of abstraction and encapsulation can (and should) be applied to any language, even without OO features.Wildawildcat
U
0

I think a good controller/model separation could be made by letting controller do "syntactic" dependent operations with no/few business logic involved and use model to perform "semantic" related operations.

A good example of that separation is:

you may perform regexp check of an email in controller but you won't perform ldap matching of that email in controller.

Undertow answered 24/6, 2010 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.