Welcome Guest, Not a member yet? Register   Sign In
Is accessing post values directly in a model a good idea?

Both ways work but I am more interested to know which one is good practice :

1. Somecontroller.php

$name = $this->input->post['name'];


2 Somemodel_model.php

function modelfunction()
$name = $this->input->post['name'];

Should models be directly accessing values from the view(post data)? Isnt it better that controller passes the data and controls what model gets from the views?

I am very new to MVC so still picking up concepts so pardon me if my question are a little silly.


25 views and no answer yet Sad. Is there something fundamentally wrong with my question?

Sometimes I use $_POST directly in the models..

But I guess we'll have to wait for an MVC guru or something =P

This is one of those questions where there pretty much isn't a right answer.

I like to make this possible as well because it does save some duplicate code, on the other hand I might need to edit stuff in a way that I can't just call the model and let it handle the post.
My advice: make it possible to do it both with post and with passing variables.

I tend to let my models do the validation work as well and I don't always need full validation, sometimes just a couple of fields. At the same time not all fields can always be used from post directly (to keep things simple for users). I've solved this by calling from the controller like this (fake example):
$fields = array(
    'name', // which of course means 0 => 'name',
    'email' => $this->input->post('email') . '@' . $this->current_user->get_domain()

And the Email_address model has the following:
protected $fields_validation = array(
    'name' => 'trim|required|min_length[4]',
    'email' => 'trim|required|valid_email',
    'some_value' => 'trim|required'

public function update( $fields = array() )
    // When no fields were given get all fields from the $fields_validation array
    // which holds the validation rules for all the model's fields
    if ( empty( $fields ) )
        $fields = array_keys( $this->fields_validation );

    foreach ( $fields as $key => $value )
        // If the key is an int it was given without value so fetch the value
        // from post and use the current $value as the key.
        if ( is_int( $key ) )
            $fields[$value] = $this->input->post($value, TRUE);
            unset( $fields[$key] );
    // etc...

I think you can get the idea?

Theme © iAndrew 2016 - Forum software by © MyBB