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:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With