Check form data - in model or in controller?
In CodeIgniter, I have such model and controller for comment posting with AJAX
model:
class Items_model extends Model {
function add_comment($item_id, $user_id, $text, $type)
{
$data = array(
'item_id' => $item_id,
'user_id' => $user_id,
'text' => $text,开发者_如何学运维
'type' => $type,
'created_at' => mktime()
);
$this->db->insert('comments', $data);
return $this->db->insert_id();
}
controller:
class Items extends Controller {
function add_comment()
{
$this->load->helper('date');
$item_id = $this->input->post('item_id', TRUE);
$text = $this->input->post('comment_text', TRUE);
$type = $this->input->post('type', TRUE);
$user_id = $this->session->userdata('user_id'); // user id, must be logged in
$this->Items_model->add_comment($item_id, $user_id, $text, $type);
$response = array(
'message' => 'Thank you!'
);
echo json_encode($response);
}
In controller or in model should I control that data from form: $item_id and $text are not null, $user_id is set and user has logged in? And how?
Best, Kirill.
I would validate at the controller level and then set default values in the model level if you're working by yourself. Ideally, you would have validation and error handling at each level, and even do some validation on the client side as well. On large projects, it might be the case that one developer is building the model and another is building the controller. If each validates at their own level, then not only will it make the application more secure, but it will let each know that they're accessing the functions correctly, etc.
This person (on the CodeIgniter forum) disagrees, saying you should scrub data where it gets processed, not where it gets passed. That makes sense to me, because it would only have to happen in one place, not in every controller that might use the model.
精彩评论