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

[eluser]Jelmer[/eluser]
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):
Code:
$fields = array(
    'name', // which of course means 0 => 'name',
    'email' => $this->input->post('email') . '@' . $this->current_user->get_domain()
);
$this->email_address->update($fields);

And the Email_address model has the following:
Code:
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?


Messages In This Thread
Is accessing post values directly in a model a good idea? - by El Forum - 10-10-2010, 07:50 AM



Theme © iAndrew 2016 - Forum software by © MyBB