在 PHP 中创建视图 - 最佳实践 [英] Creating Views in PHP - Best Practice

查看:39
本文介绍了在 PHP 中创建视图 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与另外 2 位开发者一起开发一个网站.我只负责创建视图.

数据在一个对象中可用,我有 getter 来读取数据然后创建 XHTML 页面.

在不使用任何模板引擎的情况下执行此操作的最佳做​​法是什么?

非常感谢.

解决方案

如果不想使用模板引擎,可以利用 PHP 的基本模板功能.

实际上,你应该只写HTML,当你需要输出一个变量的值时,用<?php打开一个PHP部分,用?>关闭它代码>.对于示例,我将假设 $data 是您的数据对象.

例如:

getWhatever();?></div>

请注意,所有 PHP 控制结构(如 ifforeachwhile 等)也有一个可以用于模板.您可以在他们的 PHP 手册页中查找这些内容.

例如:

<?php if ($data->getAnother() > 0) : ?><span>X</span><?php 其他:?><span>Y</span><?php endif;?>

如果您知道将在服务器上启用短标签使用,为简单起见,您也可以使用它们(不建议在 XML 和 XHTML 中使用).使用短标签,您可以简单地用 打开 PHP 部分,然后用 ?> 关闭它.另外,<?=$var?> 是回显某些东西的简写.

第一个带有短标签的示例:

<div id="fos"><?=$data->getWhatever()?></div>

<小时>

不过,您应该知道在哪里使用换行符和空格.浏览器将收到您编写的相同文本(PHP 部分除外).我的意思是:

编写此代码:

不等同于这个:

<img src="y.jpg" alt=""/>

因为在第二个中,您在 img 元素之间有一个实际的 \n,它将被浏览器转换为空格字符并显示为实际空格如果它们是内联的,则在图像之间.

I am working on a website with 2 other developers. I am only responsible to creating the views.

The data is available in an object, and I have getters to read the data then create XHTML pages.

What is the best practice to do this, without using any template engine?

Thanks a lot.

解决方案

If you don't want to use a templating engine, you can make use of PHP's basic templating capabilities.

Actually, you should just write the HTML, and whenever you need to output a variable's value, open a PHP part with <?php and close it with ?>. I will assume for the examples that $data is your data object.

For example:

<div id="fos"><?php echo $data->getWhatever(); ?></div>

Please note that, all PHP control structures (like if, foreach, while, etc.) also have a syntax that can be used for templating. You can look these up in their PHP manual pages.

For example:

<div id="fos2">
<?php if ($data->getAnother() > 0) : ?>
    <span>X</span>
<?php else : ?>
    <span>Y</span>
<?php endif; ?>
</div>

If you know that short tag usage will be enabled on the server, for simplicity you can use them as well (not advised in XML and XHTML). With short tags, you can simply open your PHP part with <? and close it with ?>. Also, <?=$var?> is a shorthand for echoing something.

First example with short tags:

<div id="fos"><?=$data->getWhatever()?></div>


You should be aware of where you use line breaks and spaces though. The browser will receive the same text you write (except the PHP parts). What I mean by this:

Writing this code:

<?php
    echo '<img src="x.jpg" alt="" />';
    echo '<img src="y.jpg" alt="" />';
?>

is not equivalent to this one:

<img src="x.jpg" alt="" />
<img src="y.jpg" alt="" />

Because in the second one you have an actual \n between the img elements, which will be translated by the browser as a space character and displayed as an actual space between the images if they are inline.

这篇关于在 PHP 中创建视图 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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