I'm very new in php. So i realize from my first steps is this language that we have the opporunity to combine or not php code and html code. Could anyone answer to me, which is the most appropriate way:To combine html and php code or to keep them seperately?and why?
Asked
Active
Viewed 699 times
1
-
maybe this will help: http://stackoverflow.com/questions/1677992/why-use-a-templating-engine-with-a-framework – Book Of Zeus Nov 28 '11 at 01:33
-
This is somewhat related but not exactly the same thing - its about a templating engine (Twig, Smarty, etc) vs doing templating directly with PHP - separated from the "actual" code in both options. Tho some of the answers are relevant to this question too. – shesek Nov 28 '11 at 01:36
2 Answers
1
Combining PHP and HTML is always a bad idea (edit: of course as long as you are mixing data, logic and presentation, as you are going to do...) and an headache for future developers of your application. But, as you've just started learning PHP, i would suggest "separating" code blocks from HTML as much as you can, like this:
<?php
// Code block to construct main variables
$enabled = true;
$persons = array('Me', 'You', 'Stack Overflow');
?>
<span>enabled: <?php echo $enabled ? 'yes' : 'no'; ?>.</span>
<ul>
<?php foreach($person as $p) {>
<ul>Person: <?php echo $p; ?></ul>
<?php } ?>
</ul>
Then go more in deep trying a template engine like Twig or Smarty.

gremo
- 47,186
- 75
- 257
- 421
-
1Always a bad idea? You realize that PHP was built initially to be combined with HTML, and frameworks such as CodeIgniter also encourage use of PHP-parsed "templates" for efficiency? – Jared Farrish Nov 28 '11 at 01:42
-
@JaredFarrish PHP was created in 1995, web application today are more and more complex and thus need a separation of concerns to ensure maintainability, reuse and flexibility (read: change proof). – gremo Nov 28 '11 at 01:45
-
3Indeed, "always" is too much of a generalization. You should not mix your *business logic* into your *templating*. The templating itself may very well be done using mixed PHP and HTML, since that's exactly what PHP was created for. – deceze Nov 28 '11 at 01:47
-
@deceze agree, but the original question is about mixing php and html, that is business logic, possibly the model and the view. Thus my answer. But if data and logic are separated yes, mixing php and html can be fine, but templating helps with function and helpers that make the code much better. – gremo Nov 28 '11 at 01:51
-
2
1
Separate the business logic and UI logic can make the code look more clearly. the MVC pattern

vince
- 11
- 1