Johan Broddfelt
/* Comments on code */

Start at the index

Why do I want my main page to be called index.php. That is because most webmasters are by default setup to look for files called index.* and perhaps main.* in some order and the first file it encounters will be the first file that it will read. Why .php? Well because HTML-files can not run php code. And that is what we want to do.

So what goes into my index.php file?

<?php
require_once('global.php');

ob_start();
require_once("main_template.php");
$html = ob_get_contents();
ob_end_clean();

echo $html;

function printContent() {
}

The string <?php in the beginning tells the server that with in <?php and ?> is a block of php-code. So the server knows to execute that code properly.
Then I have a require_once('global.php');. This includes the file global.php and all containing code into index.php. Why can't I put it there right away? You most definitely could. But then you would have to write it in all fills you want to use as starting points in your application. I mainly use three starting points. index.php, report.php and ajax.php. Where index.php contains the template for the website, and report.php shows the content without menu and other elements. Just the style to make it look the same, but printer friendly. Finally the ajax.php is used without any template so that it can return pure unstyled xml, json or some other format.
So now I can just write require_once('global.php'); in the top of those and I get access to all the necessary components. And I do not have to update in several places if I need to change something.

Then I require the main_template.php. The main_template contain the basic layout of the site. The parts that do not change when I browse the site. So if it does not change, why keep it out of the index.php. That is because the template will probably contain quite a lot of HTML-code and we want to separate the php from the HTML as much as we can. And we also have the possibility to easily choose other templates for specific sites if we want to later. For different parts of the site or just to test new layouts before we decide on which one to use.

The ob_start() and ob_get_contents() stores the HTML as it is being generated. It gives us the possibility to manipulate the HTML, before sending it to the browser.

The command echo $html; will send all the HTML to the browser.

At the end we have a function called printContent() that takes no parameters. This function will be called from the main_template.php at the location we want to put the content.

So provided you add the two additional files to your directory, the site will now run like a charm. Displaying absolutely nothing.

Next we will take a look at the main_template.php and some HTML.

- framework, php, software

Follow using RSS

<< Building your own framework Main_template.php and html >>

Comment

Name
Mail (Not public)
Send mail uppdates on new comments
0 comment