Welcome Guest, Not a member yet? Register   Sign In
Avoiding deep-nesting of if/else statements in controllers?
#1

[eluser]sorenchr[/eluser]
You know the deal.. halfway through working on your controller that handles logins your code looks something like this:

Code:
if($this->form_validation->run() == TRUE)
{
    // Check if user validates using email/password combination
    $this->load->model('accounts');
    if(is_array($user_array = $this->accounts->get_user_array($this->input->post('login-email'))))
    {
        // Does the password entered match the password in the db?
        if(crypt($this->input->post('login-password'), $user_array['password']) == $user_array['password'])
        {
            // Correct password
        }

        else
        {
        // Incorrect password
        }
    }

    else
    {
        // no user exists by that email
    }
}

else
{
    // form did not validate
}

Is there a way to avoid this? Possibly by 'stopping' the controller if a single statement is true? Like:

Code:
if(statement)
{
  // Stop controller here
}
#2

[eluser]skunkbad[/eluser]
That's not a very deeply nested example if you ask me.
#3

[eluser]stuffradio[/eluser]
That looks about right in accordance to the way I made my authorization stuff.
#4

[eluser]Buso[/eluser]
I only do the validation in the controller, the other stuff in the model, so I don't have to see it every time.

Also, if the TRUE or FALSE block is short enough, you can avoid using 'if' like this:
Code:
$this->form_validation->run() OR $this->login() // if validation fails, show the login again
// here keep trying to make the login fail

In this case, the FALSE block is only a function call. Then I can do that.

If it was the oposite case, you could change the condition to:
Code:
! $this->form_validation->run() OR redirect('success') // if validation passed, show the success page

or
Code:
$this->form_validation->run() AND redirect('success') // if validation passed, show the success page

or whatever fits the case
#5

[eluser]sorenchr[/eluser]
Thanks for the replies. @Buso thanks for the suggestions




Theme © iAndrew 2016 - Forum software by © MyBB