I read somewhere that you should separate you web pages into 3 tiers: Fetch, Logic, Presentation.
- Fetch: Grab information from database/session etc
- Logic: Calculate what you need
- Presentation: Display the HTML
So first off, is this a good idea? I can see some clear benefits (organization, easy modification). Secondly, seeing as with this model echoing out HTML is no good, should I store the HTML I want in variables?
Example:
<?php
/** fetch **/
include("session_validator.php");
$secret = $_GET['secret'];
mysql_connect($host, $user, $pass);
// connect and query
$username = mysql_result($result, 0, 'username');
/** logic **/
if (isset($secret)) {
$message = "You know the secret!";
} else {
$message = "The secret is wrong";
}
/** presentation **/
?>
<html>
<body>
Username: <?php echo $username; ?> <br>
Secret? <?php echo $message; ?>
</body>
</html>
To reiterate my question, is storing my information in $message and closing off the PHP section before presentation a good idea? Or am I misunderstanding the whole tiered concept?
This design is often referred to as MVC (Model View Controller), and it is a bit different than what you described:
I think it’s a good pattern because it allows for clear separation and easy maintenance. It also allows you to separate the work between the front-end and back-end (specifically if you have different developers for each side!).
As for the echoing part, the only place where you would echo HTML is in your View, so there’s no problem there.
I suggest you take a look at a well documented framework (such as codeigniter) and start reading.