user509006
user509006

Reputation: 107

Why save output until the end?

Very quick question about programming practices here:

I've always used echo() to output HTML code to the user as soon as it was generated, and used ob_start() at the same time to be able to output headers later in the code. Recently, I was made aware that this is bad programming practice and I should be saving HTML output until the end.

Is there a reason for this? What is it, and why isn't output buffering a good alternative?

Thanks!

Upvotes: 2

Views: 265

Answers (3)

alex
alex

Reputation: 490607

It is good to handle all sorts of things before you output in a view - for example, you may need to send additional headers such as Location and Set-Cookie.

Also, you never know what kind of view you will need - this response this time is HTML, but what if you want it as JSON or XML later? You'll have a difficult time restructuring.

If you had left all output to a final view, you could swap the HTML for an XML template.

Upvotes: 1

deceze
deceze

Reputation: 522597

Some thoughts, not necessarily in order.

  • Using echo to output HTML is messy. PHP is a template language, you can break out of it if you need to output HTML:

    <?php echo "<div id=\"foo\">" . $bar . "</div>"; ?>
    

    vs

    <div id="foo"><?php echo $bar; ?></div>
    
  • Producing HTML first and outputting headers later is messy logic. Decide what you want to send first, then send appropriate headers, then produce the content.
  • Buffering HTML to send headers later itself is not really a problem, but it's an indicator of badly structured flow.
  • Your apps could likely benefit from some compartmentalization/breaking down of logical steps.

Look into the MVC pattern.

Upvotes: 2

Ben
Ben

Reputation: 57318

Whenever any HTML is sent to the browser, headers are received/created. PHP can't send any more headers after this happens. So, by sending code "early", you're disabling PHP's ability to send headers, and limiting the flexibility of your code (either now or for future changes).

Upvotes: 1

Related Questions