Welcome Guest, Not a member yet? Register   Sign In
Controller logic
#1

[eluser]Unknown[/eluser]
Hi all

Recently started using CI for a few hobby projects - awesome!

I've had no real problems thanks to Google and searching these forums, but there is one small thing that's bugging me.
It's not causing me as issue with the code not working, but rather a workflow / readability issue.

In some cases I'm ending up with controllers that have a lot of nested if/then/else statements. I am wondering if this is normal given their name, or if I can keep things a bit more tidy?

For example:

Code:
class Booking extends CI_Controller
{

function index()
{

  if ($this->Bookingmodel->bookingSystemOpen())
  {
   //check to see if the var is set
   if($this->input->get_post('somevar'))
    {
    $var = $this->input->somefunction('id')
    
     If($var == $somevalue)
     {
     //Do something - Maybe more conditions!
    
     }
     else
     {
     //Set view data
     $data['pagetitle'] = 'Error';
     $data['title'] = 'Error';
     $data['maintext'] = 'Some message';
     $this->load->view('statusPage', $data)
     }
    
    
    }
    else
    {
     //Set view data
     $data['pagetitle'] = 'Error';
     $data['title'] = 'Error';
     $data['maintext'] = 'Some message';
     $this->load->view('statusPage', $data);  
    }
    
  }
  else
  {
   //Set view data
   $data['pagetitle'] = 'Error';
   $data['title'] = 'Error';
   $data['maintext'] = 'The system is closed';

   $this->load->view('statusPage', $data);
  }


}
}

This seems messy at best, although it works fine. Some of the files I've got had even more nested conditions in them.

I looked into exceptions, but my current understanding is that they should only be used for exceptional situations that shouldn't happen, as opposed to just catching normal work-flow conditions that are expected. I've not really used them yet in CI, but if this is the best route I'll get right on it.

My next line of testing is to try and put commonly used conditions into a higher controller and extend that. For example, not checking for the user being logged-in in each controller, checking the system is 'open' (it's a basic booking system that needs the ability to be closed) and so on. I'd assume that's a much more sensible approach?
That would also cut down on much replication of loading a status page in each controller when one of these conditions fail as I'd be extending from one that already handles this.

Any thoughts?

Many thanks for your time.




Theme © iAndrew 2016 - Forum software by © MyBB