Idiomatic PHP web page creation - php

My PHP experience is rather limited. I've just inherited some stuff that looks odd to me, and I'd like to know if this is a standard way to do things. The page which shows up in the browser location (e.g. www.example.com/example_page) has something like:
<?
$title = "Page Title";
$meta = "Some metadata";
require("pageheader.inc");
?>
<!-- Content -->
Then pageheader.inc has stuff like:
<?
#$title = ($title) ? $title : "";
#$meta = ($meta) ? $meta : "";
?>
<html>
<head>
<title><?=$title?></title
</head>
<!-- and so forth -->
Maybe others find this style useful, but it confuses me. I suppose this could be a step toward a rudimentary content management system, but the way it works here I'd think it adds to the processing the server has to do without reducing the load on the web developer enough to make it worth the effort.
So, is this a normal way to create pages with PHP? Or should I pull all this in favor of a better approach?
Also, I know that "<?" (vs. "<?php" ) is undesirable; I'm just reproducing what is in the code.

Well, it's certainly not an invalid way to do it - but it might be a little cumbersome to read and maintain. I wouldn't say there's a "normal" way to do anything like this in PHP. At the end of the day, you're outputting variables into HTML - so there aren't a variety of options without using a dedicated templating engine (and/or heading towards a more MVC-based approach, as mentioned by ryeguy).
My suggestion: if it doesn't suit your preferred style, change it. The most important thing, if you're going to be developing and maintaining it, is that you can work with it comfortably, and efficiently.

It's kind of on the right track towards MVC. MVC is all about separation of concerns. The idea here is that the first snippet sets values, and then pageheader.inc outputs them. This keeps logic out of the view.
It's done very sloppily.

PHP is a very fragmented community with no "standard" way of doing things. That said, it appears the pageheader.inc example you posted can be simplified. The code at the top is doing you no good. This alone would suffice:
<html>
<head>
<title><?=#$title?></title>
</head>
If you're looking for some direction on architecture and best practices, I'd highly recommend checking out a popular PHP framework like Codeigniter or Kohana.

There are essentially two approaches you can use, and they are inverses of each other. You have an example of one approach, where each page has its own content is responsible for including the header, footer, and other common data. There is nothing particularly wrong with this approach. The second approach is to have a single page that is responsible for including the header, footer, and content. This is far more common applications using popular PHP frameworks.

I've used that style a lot on simple sites like 5-10 page brochure-ware sites where I want some centralised code e.g creating menus and page headers from a few variables, but don't want a full-blown MVC structure as it's be overkill.

Related

Is it bad to include header and footer as a template?

I was wondering if it's the right thing to include the tags like etc via another page.
What I mean by that is:
<?php include_once("header.php")?>
The content for each individual page
<?php include_once("footer.php")?>
Header.php contains:
<!DOCTYPE html>
<head>
<title>My Website</title>
</head>
<body>
Footer.php contains:
</body>
</html>
I am using it that way because when I have a lot of pages, it's a lot easier to just change one/two page(s). That way I spare time.
But the question is, is it bad to use a "template" style for my website?
( I saw some similair questions like this one but they didn't really answer my question, that's why I started a new topic - Sorry if it's wrong )
No problem with this I think - it's certainly better than duplicating the same content across multiple pages. Don't Repeat Yourself is a core tenant of programming, and this approach helps in that regard. The performance impact of the PHP includes is absolutely minimal and not worth worrying about, compared to advantage of easier maintenance.
You might be able to go further still though. Do you really need to repeat the includes on every page ? If all the pages have identical headers and footers, then you could make just one page that has them, and an area for dynamic content in the middle instead (this is the approach ASP.NET takes).
No, this is great. You will actually find there are more and more things you would like to move into included files, for example the sidebar for your website could be in its own file. This is exactly what PHP what made for, to allow for easier maintenance of your website.
Any PHP will be slower than only HTML. For example people use cacheing plugins for wordpress sites, so just HTML will be requested and the php server wont have to work as hard, and the page will be quicker. But the benefits of using PHP clearly outweigh this with the popularity of wordpress.
All php calls are made once, so multiple calls of php is not like multiple calls for css files or JavaScript.
As the site grows you will be happy to make one change that will affect all pages, rather than have to change each page. A simple example is a seasonal greeting in the header. Simple to ad and take away with your template. not so without. And that is before the more obvious link changes.
This is a good direction, just don't repeat yourself. Anyway, to get some more robustness from this templating idea you can try to take a look on the following libraries:
Twig : http://twig.sensiolabs.org
Smarty: http://www.smarty.net

What architecture should I use for writing my first dynamic website in PHP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I just want to build my first dynamic Website. I want to use PHP, MYSQL, AJAX, HTML, CSS
I have some beginner Questions:
Should the Header and Navigation Bar excluded in a header.php and print out with echo?
Should the design tags in the echo in php (like: <a>1 Test test</a>) or only return the the data
Is there a good example for making dynamic websites?
My main problem is that i don't know how to make a clear structure. Where to make the right design (print out in the php ?)
If it is really your first website, I'd actually recommend using nothing in terms of frameworks. This buys you some time to get comfortable with HTML/CSS, SQL and PHP, without overloading you with higher-level principles such as MVC (model/view/controller) and others. I'm mostly concerned that starting with a framework right away makes the learning curve to steep, and skips over things such as getting comfortable with the programming language you'll be using.
You'll eventually make a mess with way, but this will only make you appreciate the frameworks more; you can then make the transition to using a framework such as CodeIgniter, Symfony or CakePHP (or others, because there's a whole bunch more).
Other frameworks that I really like working with are Play! for Java, and Rails for Ruby. Since you stated you're a beginner, you might consider these as well.
Well, to answer all your questions at once.
The only technology you need is template.
Template is a typical PHP script, however, consists mostly of pure HTML, with some PHP code only to display dynamically generated data.
Create a main site template contains both header and navigation bar and footer everything else excluding actual page content.
Then create separate pages ("sections" of your site: news.php, links.php, etc.)
But make every page of 2 parts: getting data part and displaying data part.
While getting data, not a single character should be printed out.
If some errors occurred, display an error page.
Once you get all your data with no errors - it's time to include a main template.
A typical script may look like
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
// setting title for using in the main template
$pagetitle = "Links to friend sites";
//etc
//set page template filename
$tpl = "links.tpl.php";
//and then finally call a template:
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
Eventually you may come to more complex designs, like with front controller one, but for the first site this one is both easy and powerful.
Yes, I do recommend you include header and navbar scripts from another file.. where you can maintain them independently. I think that is pretty important.
I recommend you echo/print html from php, rather than insert php into html (easier when doing things like parsing $_GET/$_POST etc)
I recommend that you create a template, and another script which has functions that print (or echo) the html tags, header, footer, title bar, navbar etc. Just include the script with the functions and all your pages can have the following structure:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION,etc
if needed */
print_html_pre_content();
print '<p>Hello, world! or other content.</p>';
print_html_post_content();
?>
I have found this to be pretty clean, and it is easy to add functionality when you get to messing around with $_GET, $_POST and $_SESSION, etc.
I'd suggest to use some template system (Smarty would be good).
It does not really matter where do you put your header and navigation bar at first glance. When do you need to exclude Navigation bar and store it separately? When you want to have ability to include different nav. bars in different parts of your website.
For example I have a website with several subdomains: about.website.dev, special.website.dev and, let's say, terms.website.dev
At about.website.dev my navigation bar's entries will be: "Who I am", "What do I do", "How cool am I"; at special.website.dev: "Goods", "Solutions", "Tips" , etc.
Your navigation bar's template is the same: just a loop though all entries, but content differs. In this case you separate navigation bar from header. If you don't use templates, you just create three files (in this case): about.nav.php, special.nav.php and terms.nav.php and then you just include appropriate navigation bar.
If your nav. bar is all the same everywhere on your website, you can store it in header.php. Once you need to separate, it will not be difficult, but still I'd suggest to use templates though just to get used to "proper website development".
Take a look at different templating systems like Smarty or Savant. I, personally, like Django's (python) templating system most. And get used to separate your view and business logic.
IMHO, you would be better off having a look at a php-based web application framework. such as the list at http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
Even though it may be a little more to learn upfront (the framework as well as php), they all have solid enough structures to develop dynamic websites with. Find one that is light enough and has good tutorials and you'll find yourself learning the php language along the way. I believe this will be easier than just using raw php at the beginning stage.
When you know more you can then make a judgement call on which frameworks you prefer and suit your needs or coding style or even revert back to raw php.
If you want a good book on the subject, try
MySQL/PHP Database Applications by Brad Bulger, Jay Greenspan and David Wall
What you are asking is pretty much a matter of taste. The more complex your application will be, the more work should go into an elaborate and maintainable structure.
My opinion is: Learn the basics first and then look at frameworks. It makes it a lot easier if you understand what happens under the hood.
Try Agile Toolkit, probably the easiest PHP UI framework to get started with designed for web software.
You'll step over many problems. http://agiletoolkit.org
Depending of the choice of framework/plain PHP, you should do it in accordance with their practices. For instance in Agile Toolkit you use templates, so you put your header and footer into templates/jui/shared.html file. It's explained in the first screencast.
If you reinvent the wheel and go ahead with plain PHP, then you should do better do include 'header.php'; . Good framework lets you NOT learn about inner workings of web software. Bad framework needs you to know everything anyway.
There's a lot of good answers here already - but just to add....
Do split functionality into separate include files - and use a consistent way of locating these files.
Do find a good PHP coding style and stick to it. e.g. horde, PEAR
Don't have code or HTML executed inline in include files - it should only do something when you specifically invoke it from your controlling script.
If you are including files which generate HTML, make sure they provide functionality for closing any tags they open. i.e. not just a 'header.php'
Since CSS and Javascript files should not be directly declared outside the HEAD of the HTML document do look at ways by which invoked functionality can add these into an existing HTML document - one obvious solution is to use a templating system combined with output buffering but you can also inject additional JS and CSS files into the HEAD section later in the document by using javascript.
Use MVC - http://www.yiiframework.com/doc/guide/1.1/en/basics.mvc
See Yii-framework http://yiiframework.com, it has all you need :)

Preferred way to combine PHP and HTML?

I learned PHP by hacking away at phpBB2, even submitting a few mods to their database, which others downloaded and used. (I don't believe phpBB2 is supported any more with phpBB3 out so long now, so the v2 mods database is no more.)
One of my favorite things about phpBB was their templates system, which let the editor completely separate the HTML and the PHP. PHP files contained PHP: logic, database queries, and activating the templates. TPL files contained templates: HTML, template variables, and specialized HTML comments to allow for conditional or repeating blocks.
However, any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed). phpBB is the only PHP I've looked at which actually separates the language and the markup language, suggesting to me that few, if any, other PHP codebases do such a thing.
I'm looking to start working with some PHP again, but this time it won't be a phpBB forum, and it will be on a team. Based on my experience, separation of PHP and HTML is uncommon (please correct me if I'm wrong on this!). However, I'm so used to that dividing line, I hate reading mixed PHP and HTML.
In the "real world" of PHP programming, what's the preferred method:
PHP files with strings of HTML
HTML files broken up with PHP blocks
PHP and HTML completely separate (I wish?)
Something else?
If you want to separate the PHP from the HTML you can use a template engine (Like smarty http://www.smarty.net/).
Personally, I see no reason to add a template system/language into the mix, when PHP is already a prefectly good solution.
My preferred approach is to separate the display from the logic of the application. This could take the form of a full blown MVC framework. However, it could also be a simple matter of how you go about writing your code.
Expansion:
Ever since making the mistake of interspersing my HTML with copious amounts of ASP code, I have tried to separate page logic from display. Within a single page, this means placing all of the page logic at the top, storing the information to be displayed in variables and then echoing them out within the HTML at the bottom of the PHP file. The only logic which appears in the HTML portion is display logic. In other words, simple error handling, ifs, loops, etc. Basically, the same stuff that you'll find in most templating languages.
My reason for avoiding templating languages is that it's yet another form of syntax that I need to worry about. What's the point? PHP provides more than I need for this purpose.
Meanwhile, you can take a simple MVC approach by separating things:
controller.php
<?php
// some application logic
$data['message'] = 'Hello, World.';
include 'view.php';
exit;
?>
view.php:
<html>
<head>
<title>
A simple 'MVC' view
</title>
</head>
<body>
<p>
<?php
echo $data['message'];
?>
</p>
</body>
</html>
This isn't without its drawbacks and issues. However, if you think you can have complete, clean separation between application logic and display, you're mistaken.
We use a customized code igniter base for MVC and just have logic and layout separated. that doesn't necessarily mean there's no php in our html, just that its not used for logic. It's perfectly okay to loop through a recordset with php code in a template imho, just don't try to talk to business objects and actually do stuff in the layout templates. You could ofcourse also look into something like tal or a million others for the templates if you really want to get rid of all php code there. I'm kinda thinking that's mostly overkill though, unless "insert special circumstance here"
edit fixed typo
In my experience, a lot of PHP development, whether for better or worse, ends up being php files connected to each other through includes that print out snippets of HTML as needed.
Mind though, most of my PHP experience is for more of a "we just need something that works" solution than a "we need the most elegant and efficient solution"
any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed).
Yeah, the general quality of code out there is embarrassing.
Whilst you can go to a full-blown templating engine of your own, that may be overkill and in many cases the limited domain-specific-languages they provide will get in your way, when you could just be writing presentation logic in PHP.
If you want to still be writing normal PHP, but without the spaghetti:
Keep action code at the top of the file or in a different file. Put only application logic here, not any kind of HTML or templating. Any information generated in this stage that needs to be displayed by the template needs to go in a variable to be passed to the templating part, not print​ed out in the middle of a load of business logic.
Take your knowledge of tag-based templating and apply it to PHP. Have a single, correctly-indented hierarchy of code for both HTML and PHP presentation logic, as if you were writing ‘well-formed’ XML (whether or not you're actually using XHTML). Avoid putting HTML in strings at all costs.
Define an easier way of calling htmlspecialchars(), because otherwise typing that all the time is going to be a real pain, and if you aren't typing it all the time you're going to have potentially security-sensitive errors.
To summarise, eg.:
<?php
// active code here
// do things
// put any errors in a $errors array
// this trivial function would presumably be in an include
//
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
?>
<body>
<?php if (count($errors)!=0) { ?>
<ul id="errors">
<?php foreach ($errors as $error) { ?>
<?php h($error); ?>
<?php } ?>
</ul>
<?php } ?>
...
</body>
In the "real world" of PHP programming, what's the preferred method:
Oh, in the real world of PHP programming, the average project has a mishmash of approaches thrown together without any thought. In the real world the code is unmaintainable, bug-ridden, and insecure. You don't want to look at the Industry Standard, because the Industry Standard is to be broken in every way.
I prefer to use a template system to minimize the amount of PHP code contained in the HTML files. I really don't see any way to entirely separate PHP from HTML, but I feel that it is sufficient to separate business logic (database) from presentation logic.
My template system is home-baked, but I'm sure you can find a variety that would work by preforming a google search.
Based on my experience, separation of PHP and HTML is uncommon
True. But lot of PHP code is written by inexperienced developers. Further, PHP does not encourage, but rather discourage writing good code, and the ability to mix HTML with programming code is one of the examples of this.
If you expect to do high quality code, to be able to easily maintain and extend it, I highly recommend using template engine or something similar. Mixing both has a huge impact on the readability of your code, and will result in something becoming worse and worse over time. Refactoring will be painful, if not impossible.
Now, you have a large choice of the way to separate HTML from PHP
The most obvious one is to use an existing layout engine. There are plenty of them, some very well done and with a very low performance impact.
You can also write your own engine. It may not be a good idea on a big project (why reinvent the wheel?), but can be a solution either on a tiny project or when you need something very specific.
The last way I use in most projects is to build XML from business layer (XML serialization is quite easy in PHP), then to use XSLT to transform this to HTML page. It enables to do websites which are much easier to maintain and more easy to understand, and, by the way, enables to access the website data programmatically (loading XML instead of HTML page) when need. On the other hand, it decreases performance hugely, so is not intended for large websites with thousands of queries per second.
Most code starts with PHP and HTML strings, then evolves into a templating system during a big rewrite. Separating content from logic up front requires design, planning and communication among the team. Using XML or JSON instead of PHP arrays as the data format makes this easier.
you can mix up PHP inside HTML or vice versa simply by adding opening <?php and closing ?> PHP tags between your HTML.
<!DOCTYPE html>
<head>
<title>Hello world as text</title>
</head>
<body>
<?php
echo "<p>Hello world</p>";
?>
</body>
</html>
For more details : https://stackhowto.com/how-to-combine-html-and-php/

separating php and html... why?

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>';
}
?>
When people talk about separating PHP and HTML they are probably referring to the practice of separating a website's 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 your 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 your 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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

Keeping my PHP pretty

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 :
one with only PHP code (no HTML) that fills variables
another with HTML and very few PHP : this is your page design
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.
Use a mvc approach.
http://www.phpmvc.net/
This is not something that you will pick up in a couple of hours. You really need to practice it. Main thing is the controller will access your model (the db layer), do stuff to your data and then send it to the view for rendering. This is oversimplified but you just need to read and practice it to understand it.
This is something I used to help me learn it.
http://www.onlamp.com/pub/a/php/2005/09/15/mvc_intro.html
Try to separate your content and layout from your code as much as possible. Any time you write any HTML in a .php file, stop and think "Does this really belong here?"
One solution is to use templates. Look at the Smarty templating system for a pretty easy-to-use option.
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?
Treat your PHP and HTML as a single hierarchy, with a single, consistent indentation structure. So a PHP enclosing-structure such as an 'if' or 'for' introduces a new level of indentation, and its contents are always a balanced set of start and end-tags. Essentially you are making your PHP 'well-formed' in the XML sense of the term, whether or not you are actually using XHTML.
Example:
<div class="prettybox">
Hello <?php echo(htmlspecialchars($name)) ?>!
Your food:
<?php foreach($foods as $food) { ?>
<a href="/food.php?food=<?php echo(urlencode($food)) ?>">
<?php echo(htmlspecialchars($food)) ?>
</a>
<?php } ?>
<?php if (count($foods)==0) { ?>
(no food today)
<?php } ?>
</div>
Be wary of the religious dogma around separating logic and markup rearing its head in the answers here again. Whilst certainly you want to keep your business-logic out of your page output code, this doesn't necessarily mean a load of overhead from using separate files, classes, templates and frameworks is really necessary for what you're doing. For a simple application, it is likely to be enough just to put the action/logic stuff at the top of the file and the page output below.
(For example from one of the comments above, doing htmlspecialchars() is page-output functionality you definitely don't want to put in the action bit of your PHP, mixed up in all the business logic. Always keep text as plain, unescaped strings until the point where it leaves your application logic. If typing 'echo(htmlspecialchars(...))' all the time is too wordy, you can always make a function with a short name like 'h' that does the same.)
From the sound of your problem, it seems you might not have much separation between logic and presentation in your code. When designing an application this is a very important consideration, for reasons exactly demonstrated by the situation your currently facing.
If you haven't already I'd take a look at some PHP templating engines such as Smarty.
In cases like that I write everything incrementally into a variable or sometimes an array and then echo the variable/array. It has the added advantage that the page always renders in one go, rather than progressively.
What I end up doing in this situation is building 'template' files of HTML data that I Include, and then parse through with regular expressions. It keeps the code clean, and makes it easier to hand pieces off to a designer, or other HTML person.
Check out the ideals behind MVC programming practices at Wikipedia
You need a framework. This will not only make your code pretty (because of the already-mentioned model-view-controller pattern, MVC) - it will save you time because of the components that are already written for it.
I recommend QCodo, it's amazing; there are others - CakePHP, Symfony.
If it's a big project a framework might be in order. If not, create some template files and at the top of the page decide which template file to include.
for example
if ($_SESSION['logged_in'])
include(TPL_DIR . 'main_logged_in.tpl');
else
include(tPL_DIR . 'main.tpl');
just a simple example
as mentioned above.. you are fixing the symptom, not the problem..
What you need is the separation of logic and presentation. Which can be done with some sort of mvc framework. Even if you don't want to go all the way with a mvc framework.. A templating engine is a must at least if your logic is complicated enough that you have trouble with what you are explaining
I strongly suggest savant instead of smarty,
you don't have to learn a new templating "language" in order to create templates, savant templates are written in php
if you don't want to use php you can define your own template "language" with a compiler
it's easily extendable by your own php objects
Separating logic from presentation does not mean that all you business logic has to be in php and your presentation logic in something else, the separation is a conceptual thing, you hae to separate the logic that prepares data form the one that shows it. Obviously the business logic does not have to contain presentation elements.
In stead of implementing templating systems on top of a templating system (PHP itself), creating overhead per default, you can go for a more robust solution like XSL Transformations, which also complies with the MVC princples (provided you seperate your data-retrieval; plus, I personally split the logic from displaying the XML with different files).
Imagine having the following information in an array, which you want to display in a table.
Array
{
[car] => green
[bike] => red
}
You easily create a script that outputs this information in XML:
echo "<VEHICLES>\n";
foreach(array_keys($aVehicles) as $sVehicle)
echo "\t<VEHICLE>".$sVehicle."</NAME><COLOR>".$aVehicles[$sVehicle]."</COLOR></VEHICLE>\n";
echo "</VEHICLES>\n";
Resulting in the following XML:
<VEHICLES>
<VEHICLE>
<NAME>car</NAME>
<COLOR>green</COLOR>
</VEHICLE>
<VEHICLE>
<NAME>bike</NAME>
<COLOR>red</COLOR>
</VEHICLE>
</VEHICLES>
Now this is all excellent, but that won't display in a nice format. This is where XSLT comes in. With some simple code, you can transform this into a table:
<xsl:template match="VEHICLES">
<TABLE>
<xsl:apply-templates select="VEHICLE">
</TABLE>
</xsl:template>
<xsl:template match="VEHICLE">
<TR>
<TD><xsl:value-of select="NAME"></TD>
<TD><xsl:value-of select="COLOR"></TD>
</TR>
</xsl:template>
Et voila, you have:
<TABLE>
<TR>
<TD>car</TD>
<TD>green</TD>
</TR>
<TR>
<TD>bike</TD>
<TD>red</TD>
</TR>
</TABLE>
Now for this simple example, this is a bit of overkill; but for complex structures in big projects, this is an absolute way to keep your scripting logic away from your markup.
Check this question about separating PHP and HTML, there are various ways to do it, including self written templating systems, templating systems such as Smarty, PHP as a templating system on it's own, etc etc etc...
I think you've two options here, either use a MVC Framework or use the lazy templating way which would put significant overhead on your code. Obviously I'm with the former, I think learning MVC is one of the best web development tricks in the book.

Categories