Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Views in PHP - Best Practice [closed]

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.

like image 962
user160820 Avatar asked Jun 03 '11 15:06

user160820


1 Answers

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.

like image 62
kapa Avatar answered Sep 24 '22 06:09

kapa