Reputation: 3970
I am wondering what is considered best practice when passing info from a controller to a model. More specifically, I am creating a user registration model within a user class that asks for certain info such as email, name, and password.
I am wondering if it is better to put parameters within the model function and pass them that way or if is better to just call the function and use the $_POST variables for the query.
Here are the two examples I am referring to.
Method 1
function register(){
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$password = $this->input->post('password_1');
$this->user_model->register_user($email, $password, $first_name, $last_name));}
function register_user($email, $password, $first_name, $last_name){
$sql = "INSERT INTO users (user_id, email, passwd, first_name, last_name, registration_date, confirmed, confirmation_code, banned)VALUES (NULL, ?, ?, ?, ?, '".date('Y-m-d')."', 'no', '1fg455675', 'no')";
$register = $this->db->query($sql, array($email, $password, $first_name, $last_name));
return $register;
}
Method 2
function register(){
$this->user_model->register_user());
}
function register_user(){
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$password = $this->input->post('password_1');
$sql = "INSERT INTO users (user_id, email, passwd, first_name, last_name, registration_date, confirmed, confirmation_code, banned)VALUES (NULL, ?, ?, ?, ?, '".date('Y-m-d')."', 'no', '1fg455675', 'no')";
$register = $this->db->query($sql, array($email, $password, $first_name, $last_name));
return $register;
}
I have removed a lot of the validation code and what not to simplify the matter so hopefully you get the idea.
Upvotes: 3
Views: 211
Reputation: 401152
I would not use $_POST
(nor its equivalent with your framework) in the Model layer : this one doesn't have to know where the data comes from.
The Model can be called from a webservice, a command-line program, or whatever, and must still work : it must not depend on anything being POSTed to the application.
The Controller is the one being called, receiving the parameters of the HTTP Request (in case of an HTTP request, of course) ; it'll then extract the data, and pass it to the layer that'll work on this data : the Model.
Upvotes: 2
Reputation: 50039
You shouldn't be accessing your POST variables from your model. This would make your model less reusable since now they rely on POST data to work. For example, at some other point if you needed a method to do the same thing, but you were getting your data from some other source (CSV) you wouldn't be able to use the same model because you've tied it in with POST.
Try to decouple them when you're working with such a structure
Upvotes: 2