为什么要保存输出直到最后?
关于编程实践的一个非常简单的问题:
我总是使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有些想法,不一定按顺序。
使用
echo
输出 HTML 很混乱。 PHP是一种模板语言,如果需要输出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:vs
Look into the MVC pattern.
每当任何 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).
在视图中输出之前最好处理好各种事情 - 例如,您可能需要发送额外的标头,例如
Location
和Set-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
andSet-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.