I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times.
Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)?
Thanks!
Don't panic, every fresh Web programmer face this problem.
You HAVE TO separate your program logic from your display. First, try to make your own solution using two files for each Web page :
Then include where / when you need it. E.G :
myPageLogic.php
<?php
// pure PHP code, no HTML
$name = htmlspecialchars($_GET['name']);
$age = date('Y') - htmlspecialchars($_GET['age']);
?>
myPageView.php
// very few php code
// just enought to print variables
// and some if / else, or foreach to manage the data stream
<h1>Hello, <?php $name ?> !</h1>
<p>So your are <?php $age?>, hu ?</p>
(You may want to use the alternative PHP syntax for this one. But don't try to hard to make it perfect the first time, really.)
myPage.php
<?php
require('myPageLogic.php');
require('myPageView.php');
?>
Don't bother about performance issues for now. This is not your priority as a newbie. This solution is imperfect, but will help you to solve the problem with your programming level and will teach you the basics.
Then, once your are comfortable with this concept, buy a book about the MVC pattern (or look for stack overflow entries about it). That what you want to do the NEXT TIME. Then you'll try some templating systems and frameworks, but LATER. For now, just code and learn from the beginning. You can perfectly code a project like that, as a rookie, it's fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With