2

My question

I'm unsure about the handling of $_POST data in a MVC architecture: Who should catch the $_POST data: The controller or the model ? Several sources say "skinny controllers, fat models", but same sources also say that a model should be strictly decoupled from the application (and example B clearly shows a "fat" model, but is not decoupled as it directly asks for POST data). For comparison let's see the same thing written in two different ways (example pseudo-code):

A.) The controller grabs $_POST values, passes it as arguments to model

// CONTROLLER
public function createSomething()
{
    $model = new Model;
    $model->createThis($_POST['stuff_from_form']);
}

// MODEL (expects argument)
public function createThis($stuff)
{
    // and here the model method does whatever it does
}

B.) The model grabs $_POST values

// CONTROLLER
public function createSomething()
{
    $model = new Model;
    $model->createThis();
}

// MODEL (expects NO argument, grabs POST data directly)
public function createThis()
{
    $stuff = $_POST['stuff_from_form'];
    // and here the model method does whatever it does
}
Sliq
  • 15,937
  • 27
  • 110
  • 143
  • 3
    Check the accepted answer on this [SO question](http://stackoverflow.com/questions/13359818/what-is-the-right-way-to-handle-post-data-in-mvc?rq=1) - should help you out – kmfk Dec 24 '13 at 23:58

2 Answers2

2

Your controller should manage all validation and only pass verified / clean data to your models. The reason for this is that you want to keep your models generic enough for re-use and all access to the models/database should be validated / cleansed before hand.

Also don't use $_POST directly if you are using something like CodeIgniter then use their handler $input->post->('name'); (or similarly for any PHP framework).

Jakub
  • 20,418
  • 8
  • 65
  • 92
1

I will go with the option A.

Because you can able to reuse the code by passing different argument later if needed, instead of going through the function contents and change your variables.

Filtering/Sanitizing your variables before pushing them to model is also a good practice, so models only have to think about the data that recieived.

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64