I know a controller does the controlling, and model does the database stuff.
How far should the model go though?
If I have an array:
array( 'first_name' => 'Thomas', 'second_name' => 'Clayson', 'email' => 'thomas@email.com' );
And this is the mysql query I need to get out of it:
INSERT INTO `users` (`name`, `email`) VALUES ("Thomas Clayson", "thomas@email.com");
What should my model look like?
Take raw data and format appropriately
public function insertUser($details){
if(!isset($details['first_name']) || !isset($details['second_name']) || !isset($details['email'])){
return false;
}
$full_name = $details['first_name']." ".$details['second_name'];
$email = $details['email'];
$query = "INSERT INTO `users` (`name`, `email`) VALUES ('".$full_name."', '".$email."')";
}
Leave the formatting up to the controller and just take the input and put it blindly into db
public function insertUser($full_name = false, $email = false){
if(!$full_name || !$email){
return false;
}
$query = "INSERT INTO `users` (`name`, `email`) VALUES ('".$full_name."', '".$email."')";
}
Something else?
My problem is that I’ve got a lot of data to put into a table, so I don’t really want to have each field as a separate arg of a function. But then I feel that putting in an array of info into the model requires me to check each index and format appropriately anyway, so there’s not much point doing it in the controller as well. Seems like twice the work.
But then again, it doesn’t feel right doing it in the model either!
So what do other people do?
P.S. The question is based on (but by no means limited to) the codeigniter framework.
Here we go again …
Model in MVC is not a class. It is a layer which contains objects with two kinds of responsibilities:
Domain business objects should not have any clue where the data comes from or where it is stored. That means there is no SQL in domain objects, because it is quite possible that there isn’t even a database and all the information goes into some remote REST API.
If you are using a database, then SQL would end up in the DAO’s ( usually implementing datamapper ).
And formating is not responsibility of neither of domain objects , nor data access objects nor even controllers.
Formating should happen in the Views, which are a full-blown objects in MVC, and not some anemic templates. View is responsible for presentational logic. It requests from the domain model layer what it needs.
You really must look up what MVC Model2 is , and how it is different from MVP.