Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MVC: How to exit from Actions/Controllers early?

In a PHP MVC framework, how can I cleanly and elegantly exit from the current controller/action, but continue normal script execution?

For example, let's say my framework normally follows this outline:

  1. Map URL to Controller/Action
  2. Instantiate Controller, call Action (capturing output)
    1. Do stuff
    2. Render View
    3. At end of Action method, continue normal operation
  3. Process output if necessary
  4. Send output to browser

Now, let's say I want to stop "normal" execution somewhere in the "Do Stuff" step to, say, render a different view, or do a header redirect, and I want to stop processing the rest of the body of the Action, but continue onto the "Process output" step

How can I achieve this the best way? My only ideas are:

//in controller
protected function redirect($url) {
    header("Location: $url");
    exit();
}

but this entirely skips the rest of the framework's execution, and dumps whatever was in the output buffer straight to the user. An alternative:

//in dispatcher
call_user_func_array(array($controller,$action),$params);
afterwards:
...

//in controller
protected function redirect($url) {
    header("Location: $url");
    goto afterwards;
}

However, this makes me twitch and goes against everything I've learned, especially because the label it's referencing is in another file completely.

So, is there any other way to achieve this?

Note: The redirect example probably should use the exit() way, because we're just redirecting to another page anyway and don't care about output. I'm looking for a general-use solution.

like image 504
Austin Hyde Avatar asked Jun 28 '10 15:06

Austin Hyde


2 Answers

In your Action method, you can collect all of your output in a string rather than printing it out. Print it out only at the end of the method. If you need to redirect or bail out, then you haven't output anything yet and you can either redirect or return from the method.

like image 94
Scott Saunders Avatar answered Oct 14 '22 09:10

Scott Saunders


Perhaps you could write a custom exception to represent a "Stop normal execution in the 'Do Stuff'" step? It's messy... but it would work.

like image 33
Richard JP Le Guen Avatar answered Oct 14 '22 11:10

Richard JP Le Guen