views:

113

answers:

3

I've always used the model as something to more or less store and execute database queries. I have heard about the fat model, thin controller concept.

The way I setup my models right now causes a lot of junk in controllers for things like validating forms, formatting data. Does form validation, file uploading and data formatting belong in the controller or the model?

I realize this question is subjective, which should create some good discussion rather than a concrete answer.

+3  A: 

Form Validation should definitely be part of the model. I generally represent each form as one model and pass it the sanitized post/get paramaters. The model can then take whatever action is necessary based on the input and use a property (optionally with a getter) to signal success or failure. In psuedo code you want it to look something like:

class Controller
{
    function action()
    {
        $input = new Input();
        $form = new FormModel($input);
        if ($errors = $form->errors())
        {
            //load the appropriate view for the errors
        }
        else
        {
            //load the appropriate view for success with an optional redirect
        }
}
aaronasterling
I think this library might help http://frankmichel.de/formgenlib/user_guide/introduction/getting_started.html
Keyo
@keyo - this is one of my gripes with CI. It requires you to have all of the information about the form (fields, labels, validation requirements) in the controller. This is just not right. If you wan't to see a good PHP MVC framework, check Kohana.
aaronasterling
@aaronasterling I wish I could use kohana or something with good architecture, but I'm stuck with CI for work.I can set it up with some ORM engines though.
Keyo
A: 

The model is what interacts with the data (most often a database). Controllers use the models to access the data.

Matthew
+3  A: 

You have two main roads to go. Thin controller/fat model or fat controller/thin model. Basicly is were you put most of the interaction. I prefer to keep at the model the major portion of the code. That way, the code is available in virtually every controller and/or lib. If the code remain at controller, it's hard (but not impossible) to use it in other controllers.

Things lije validations and other common tasks should be in a lib or helper. You can produce a set of "workers" (this is the name I give to them) to do the heavy lifting. Also, CI has a LOT of ready made libs and helpers both from the CI team and the community. Mess around the wiki to find the wealth of information available.

Hope this helps Vx

Ricardo