PHP output buffering? What's the best practise?
Further to my previous question, what's the best approach when I want to buffer PHP output until I have performed all processing? I want to buffer to leave myself the option to to redirect to an error page, which I can't do after any output.
So, what's the best practise? Use开发者_如何学C a variable $output
and keep appending to it, then output it at the end? Or use ob_str(), etc?
Is there a peformance to choose code-maintainability reason for one over the other? Or is it just personal preferance?
For me, I did this:
<?php
ob_start();
//do your process here
if($error)
{
ob_end_clean();
header('Location: /some/path.php');
exit;
}
ob_end_flush();
?>
I open a buffer with ob_start();
( http://php.net/manual/en/function.ob-start.php )
Then anything that would normally be sent to the browser (except headers) is stored in the buffer until I close it. When I want to output or manipulate the buffer, I access it like this:
$buffer = ob_get_clean();
( http://php.net/manual/en/function.ob-get-clean.php )
There are lots of other buffer options here:
http://www.php.net/manual/en/ref.outcontrol.php
This is the best way in my opinion because you don't have to keep adding items to the buffer; PHP is automatically capturing everything as long as the buffer is open.
Well written code needs no output buffering. By that I mean: first, you do all your processing, without any output. Business logic, validation, database access - this kind of stuff. After this is done, you can close the DB connection, the session, etc. because all you do is create your output based on data collected above.
This method usually results in far better maintainable code.
精彩评论