为什么要保存输出直到最后?

发布于 2024-10-10 06:06:02 字数 187 浏览 5 评论 0原文

关于编程实践的一个非常简单的问题:

我总是使用 echo() 在生成 HTML 代码后立即将其输出给用户,并同时使用 ob_start() 以便能够在代码中稍后输出标头。最近,我意识到这是不好的编程习惯,我应该保存 HTML 输出直到最后。

这是有原因的吗?它是什么?为什么输出缓冲不是一个好的替代方案?

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苦行僧 2024-10-17 06:06:02

有些想法,不一定按顺序。

  • 使用 echo 输出 HTML 很混乱。 PHP是一种模板语言,如果需要输出HTML,可以脱离它:

    " 。 $酒吧。 “”; ?>
    

    对比

  • 先生成 HTML,然后输出 headers,这是一个混乱的逻辑。首先决定要发送的内容,然后发送适当的标头,最后生成内容。
  • 缓冲 HTML 以稍后发送标头本身并不是一个真正的问题,但它是结构不良的流程的一个指标。
  • 您的应用程序可能会受益于逻辑步骤的一些划分/分解。

查看 MVC 模式。

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.

年华零落成诗 2024-10-17 06:06:02

每当任何 HTML 发送到浏览器时,都会接收/创建标头。发生这种情况后,PHP 无法再发送任何标头。因此,通过“过早”发送代码,您将禁用 PHP 发送标头的能力,并限制代码的灵活性(无论是现在还是将来的更改)。

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).

痴情换悲伤 2024-10-17 06:06:02

在视图中输出之前最好处理好各种事情 - 例如,您可能需要发送额外的标头,例如 LocationSet-Cookie

另外,您永远不知道您将需要哪种视图 - 这次的响应是 HTML,但如果您稍后想要它作为 JSON 或 XML 该怎么办?你将很难重组。

如果您将所有输出保留为最终视图,则可以将 HTML 替换为 XML 模板。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文