Welcome Guest, Not a member yet? Register   Sign In
Exit execution flow entirely from controller's constructor
#1

[eluser]novice32[/eluser]
How can I exit the execution flow altogether, from within a controller's constructor, so it's doesn't go onto the controller's method? In recent testing, if I do "return" upon finding an error in the constructor, the flow will exit the constructor but continue onto called controller method.


Thanks,
Novice32
#2

[eluser]WanWizard[/eluser]
Why would you want this? To show the user a blank page?

Wouldn't it be better to handle the error, and show an appropriate error message?
#3

[eluser]novice32[/eluser]
See this thread: http://ellislab.com/forums/viewthread/160236/

The front-end is an Adobe Flex app, so CI view aren't used. Instead, I send back a custom JSON error message which is then displayed in Flex's UI.

I could write the error checking in each controller method and exit from there, but that would be repeated code and not a best practice.
#4

[eluser]novice32[/eluser]
I guess "exit();" as opposed to "return;" works. "exit();" terminates the script altogether.
#5

[eluser]pickupman[/eluser]
If you place the method [url="http://ellislab.com/codeigniter/user-guide/general/controllers.html#output"]_output()[/url], you can controller the final output to the browser.

Why put the code in your constructor. Would it make more sense to put the conditional in the AddItem() method? By having it in the method, you wouldn't have to worry about the code execution. Or since you are using post, you can use form validation
Code:
function AddItem() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('ClientID', 'client id', 'required|trim');

        if($this->form_validation->run())
        {
           $this->ClientID = $this->input->post('ClientID'); //reads value when HTTP post is performed to controller's AddItem method
        
           // read a bunch of HTTP post values and validate.
           $this->load->model('Item_model', '', TRUE);
           $rowcount = $this->Item_model->AddItem($this->ClientID,$ItemDescription,....);

           echo json_encode(array('rowcount'=>$rowcount));
        }else{
            
            echo json_encode(array('error'=>'ClientID is required'));            
        }
    
    }
#6

[eluser]novice32[/eluser]
Hi Pickupman

In my Item controller, I have nearly two dozen methods, and each needs to ensure ClientID is passed during the HTTP post. Rather than performing the check in each controller method, I instead perform it at the constructor level since the same validation needs to be there for all methods.

I was mistakenly using "return;" upon finding an error to exit the code, but that was wrong.. I should have used "exit();" instead. With return, execution flow continues to the controller method, and with "exit()" it doesn't.

Thanks for your input.




Theme © iAndrew 2016 - Forum software by © MyBB