2

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.

Kir
  • 7,981
  • 12
  • 52
  • 69

2 Answers2

2

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.

Brian H
  • 833
  • 1
  • 5
  • 12
  • 1
    have you seen the form_validation library ? http://codeigniter.com/user_guide/libraries/form_validation.html – Ross Dec 05 '10 at 19:48
  • Yes, but how to check the $this->session->userdate(‘logged_id’) flag with Form_validator? – Kir Dec 06 '10 at 13:12
1

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.

MM.
  • 1,966
  • 4
  • 20
  • 24