PHP - 回声还是不回声? [英] PHP - To echo or not to echo?

查看:52
本文介绍了PHP - 回声还是不回声?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么更有效和/或更好的做法是回显 HTML 或有许多打开和关闭 php 标签?

显然,对于大面积的 HTML 来说,打开和关闭 php 标签是明智的.在处理诸如生成 XML 之类的事情时呢?您应该为每条数据使用一个回显打开和关闭 php 标记,还是使用包含在引号中的 XML 标记的单个回显?

解决方案

从维护的角度来看,应该尽可能将 HTML/XML 与代码分开 IMO,这样即使是非- 技术人员.

标记的同质块越多,工作就越干净.

实现这一点的一种方法是尽可能多地准备变量,并使用heredoc 语法:

//准备$var1 = get_value("yxyz");$var2 = get_url ("abc");$var3 = ($count = 0 ? "Count is zero" : "Count is not zero");$var4 = htmlentities(get_value("def"));//输出回声<<</fieldset>EOT;

当然,您会希望使用更合理的变量名称.

@stesch 在评论中指出的链接为在生成 XML 时使用 序列化器 提供了一些很好的论据,并且通过扩展,甚至是 HTML,而不是打印出来,如上图所示.我不认为在所有情况下都需要序列化程序,特别是从维护的角度来看,模板更容易编辑,但链接非常值得一读.如何在生成 XML 时避免被称为 Bozo

逻辑和内容分离的另一大优势是,如果有一天需要过渡到模板引擎或引入缓存,那么实现起来几乎是轻松的,因为逻辑和代码已经分离了.

What is more efficient and/or what is better practice, to echo the HTML or have many open and close php tags?

Obviously for big areas of HTML it is sensible to open and close the php tags. What about when dealing with something like generating XML? Should you open and close the php tags with a single echo for each piece of data or use a single echo with the XML tags included in quotations?

解决方案

From a maintenance perspective, one should have the HTML / XML as separate from the code as possible IMO, so that minor changes can be made easily even by a non-technical person.

The more a homogeneous block the markup is, the cleaner the work.

One way to achieve this is to prepare as much as possible in variables, and using the heredoc syntax:

// Preparation

$var1 = get_value("yxyz");
$var2 = get_url ("abc");
$var3 = ($count = 0 ? "Count is zero" : "Count is not zero");
$var4 = htmlentities(get_value("def"));

// Output  

echo <<<EOT

 <fieldset title="$var4">
   <ul class="$var1">
     <li>
       $var2
     </li>
   </ul>
  </fieldset>

EOT;

You will want to use more sensible variable names, of course.

Edit: The link pointed out by @stesch in the comments provides some good arguments towards using a serializer when producing XML, and by extension, even HTML, instead of printing it out as shown above. I don't think a serializer is necessary in every situation, especially from a maintenance standpoint where templates are so much more easy to edit, but the link is well worth a read. HOWTO Avoid Being Called a Bozo When Producing XML

Another big advantage of the separation between logic and content is that if transition to a templating engine, or the introduction of caching becomes necessary one day, it's almost painless to implement because logic and code are already separated.

这篇关于PHP - 回声还是不回声?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆