views:

455

answers:

11

So I have seen some comments on various web sites, pages, and questions I have asked about separating php and html.

I assume this means doing this:

<?php

myPhpStuff();

?>

<html>

<?php

morePhpStuff();

?>

Rather than:

<?php

    doPhpStuff();

    echo '<html>';

    ?>

But why does this matter? Is it really important to do or is it a preference?


Also it seems like when I started using PHP doing something like breaking out of PHP in a while loop would cause errors. Perhaps this is not true anymore or never was.


I made a small example with this concept but to me it seems so messy:

<?php

$cookies = 100;
while($cookies > 0)
{
    $cookies = $cookies -1;
?>
    <b>Fatty has </b><?php echo $cookies; ?> <b>cookies left.</b><br>

<?php

} 

?>

Are there instances when it is just better to have the HTML inside the PHP?

<?php

$cookies = 100;
while($cookies > 0)
{
    $cookies = $cookies -1;

    echo'<b>Fatty has </b> '.$cookies.' <b>cookies left.</b><br>';
} 

?>
+1  A: 

I kick off with: the first one you can open in a WYSIWYG editor, and still see some markup, which might makes it easier to maintain.

Gidon
A: 

I don't know how in php but in asp.net separation has the following advantages. 1. separated code is easy to understand and develop 2. designer can work in html in the same time developer can write a code

ArsenMkrt
For point 2, this would on work in php if the model and the view files were separate else it would just overwrite when each user saves the file.
Oliver Stubley
+2  A: 

Benefits of the first method (separating PHP and HTML):

  • You don't need to escape characters

  • It's also possible for code editors to highlight/indent the markup.

  • It's arguably easier to read

  • There is no downside to this method, compared to the second method.

Jeff Meatball Yang
+2  A: 

Functionally: they both will work, so ultimately it is a preference.

Yet, you might consider that comments are a preference as well, your code would compile and run exactly the same without comments. However most people would agree comments are essential to writing and maintaining good code. I see this as being a similar subject matter. In the long run it will make it easier to read and maintain the code it if the two are separated.

So is it important? I would say Yes.

Gnatz
+15  A: 

When people talk about seperating PHP and HTML they are probably referring to the practice of separating a web sites presentation from the code that is used to generate it.

For example, say you had a DVD rental website and on the homepage you showed a list of available DVDs. You need to do several things: get DVD data from a database, extract and/or format that data and maybe mix some data from several tables. format it for output, combine the DVD data with HTML to create the webpage the user is going to see in their browser.

It is good practice to separate the HTML generation from the rest of the code, this means you can easily change you HTML output (presentation) without having to change the business logic (the reading and manipulation of data). And the opposite is true, you can change your logic, or even you database, without having to change your HTML.

A common pattern for this is called MVC (model view controller). You might also want to look at the Smarty library - it's a widely used PHP library for separating presentation and logic.

Steve Claridge
+1  A: 

Hello Ian,

It says that what you put in echo '' it is first processed by the programming language and then sent to the browser, but if you directly put there html code without php, that code will load faster because there is no programming involved.

And the second reason as people above said is that you should have your 'large programming code' stored separately of the html code, and in the html code just put some calls to print results like 'echo $variable'. Or use a template engine like Smarty (like I do).

Best regards, Alexandru.

Alexandru Trandafir Catalin
+4  A: 

It is very important to separate application logic from presentation logic in projects. The benefits include:

  • Readability: Your code will be much easier to read if it does not mix PHP and HTML. Also, HTML can become difficult to read if its stored and escaped in PHP strings.
  • Reusability: If you hard-code HTML strings within PHP code, the code will be very specifc to your project and it won't be possible to reuse your code in later projects. On the other hand, if you write small functions that do one task at a time, and put HTML into separate template files, reusing your code in future projects will be possible and much easier.
  • Working in a team: If you are working in a team that contains developers and designers, separation of application logic and presentation templates will be advantageous to both. Developers will be able to work on the application without worrying about the presentation, and designers (who don't necessarily know PHP very will) will be able to create and update templates without messing with PHP code.
Ayman Hourieh
+4  A: 

for pages that contain a lot of HTML, embedding PHP code into the page could be easier. this is one of the first intentions behind PHP. anyway when you are developing an application with lots and lots of logic, different types of connectivity, data manipulation, ... your PHP code gets too complicated if you want to just embed them in the same pages that are shown to users. and then the story of maintenance begins. how are you going to change something in the code, fix a bug, add a new feature?

the best way is to separate your logic (where most of the code is PHP) in different files (even directories) from your page files (where most of the code is HTML, XML, CSV, ...).

this has been a concern for developers for so many years and there are recommendations to handle these general problems, that are called design patterns.

since not everyone has the experience, and can apply these design patterns into his application, some experienced developers create Frameworks, that will help other developers to use all the knowledge and experience laying in the hear of that framework.

when you look at toady's most used PHP frameworks, you see that all of them put code into PHP Classes in special directories, make configurations, and .... in none of these files you see a line of HTML. but there are special files that are used to show the results to users, and they have a lot of HTML, so you can embed your PHP values inside those HTML pages to show to users. but remember that these values are not calculated on the same page, they are results of a lot of other PHP codes, written in other PHP files that have no HTML in them.

farzad
I think I am seeing the concept behind separation but couldn't it be easy to start to have too many files that are just PHP and that degrade from the usefulness of separating them in the first place?Should there be some balance?
ian
+1  A: 

Ouch!

All of the examples in your question are perfectly impossible to read. I'd say, you do yourself and those, who might read your code a great favour and use a template engine of sorts, say, Smarty. It is extremely easy to set up and use and it WILL separate your code from presentation. It doesn't require you to put everything in classes, it just makes sure, that your logic is in one file and presentation - in another one.

shylent
What makes them hard to read. Aren't the a bit small and simple to be unreadable.I was pointed to smart early but I guess what I am trying to learn here is just the general concept behind it and I would rather learn to do it myself.What would the the proper way to separate or format my examples for readability and separation?
ian
Well, take a look at the third code sample in your original post. You open a php block and first thing we see is a _closing_ brace? That looks very wrong to me. To be honest, I really wish, that, when I've just started using php (it was some time ago), I did not bother with echo at all and just used some really simple template engine, like aforementioned smarty. It is a very small step to make, but, making that step, you instantly begin to write infinitely better (in terms of readability and maintainability) code.
shylent
Yes I am starting to get an idea of it I think and how it makes things clearer and what I am really asking about in my question is not separation but modes (breaking out of PHP or not) so I will ask a new question that I think.
ian
+3  A: 

I find it preferable to separate application logic from the view file (done well with CodeIgniter framework with MVC) as it leaves code looking relatively tidy and understandable. I have also found that separating the two leaves less margin for PHP errors, if the HTML elements are separated from the PHP there is a smaller amount of PHP that can go wrong.

Ultimately I believe it is down to preference however I feel that separation has the following pros:

  • Tidier Code
  • Less of an Error Margin
  • Easy to Interpret
  • Easier to change HTML elements
  • Easier to changed Application Logic
  • Faster Loading (HTML is not going from Parser->Browser it goes straight to browser)

However some cons may be:

  • It only works in PHP5 (I Believe, could be wrong, correct if needed)
  • It may not be what one is used to
  • Untidy if done incorrectly (without indentation etc, however this is the same with anything)

But as you can see, the pros outweigh said cons. Try not to mix the two also, some separation and some intergration - this may get confusing for yourself and other developers that work with you.

I hope this helped.

Oliver Stubley
Yes thanks. I think it may have not worked in older PHP versions... Breaking loops and such as I mentioned above.
ian
Yeah I thought that could've been it, not entirely sure if I was correct or not but I thought i'd heard it mentioned, I've done most of my php in PHP5 so haven't really had to deal with such issues
Oliver Stubley
+8  A: 

Let's make it clear what is not separation

  • you switch from php mode to html mode
  • you use print or echo statements to write out html code
  • you use small php snipplets inside html files

If you do this, there is no separation at all, no matter if you escape from php to html blocks or do it the other way and put php code into html.

Have a look at a good templating engine, there are a plenty of reasons in the "why use ...." parts of the manuals. I'd suggert www.smarty.net especially http://www.smarty.net/whyuse.php

It will answer all your questions now you have.

Csaba Kétszeri
Thank! Most places I see a reference to separation has been in a tutorial or example code on a web site and I guess people are referring to switching between PHP mode and HTML mode.I have taken a look at Smarty and I get the concept now.Is the general idea to have my PHP page... that then references my HTML output page and then that HTML page would have whatever minimum PHP output variables in it? Say login.php ->includes output.html that has inside it a few <? echo $name?> items.
ian