May
31
2006

How to: Create a site through one index.php controller file

Here is a simple example to demonstrate an easily maintainable way of setting page loading based on the current URL. It holds all of your available pages in an associative array .. This could easily be pulled from a database.

I have also included template code to generate a simple menu for you.. You could of course just construct the URL’s by hand in your templates if this does not serve your needs.

For brevity, I did not include any css or table structure for the index.tpl file.

index.php

Code:
<?php
/**
* Website controller
* @author www.ideamesh.com
*/

//Include and instantiate Smarty
include(’Smarty.class.php’);
$smarty =& new Smarty();

//Setup the url var we are looking for to control page display
$page_var = ‘page’;

//Using the $_REQUEST scope so that the page can be passed in via $_POST or $_GET
$page_request = $_REQUEST[$page_var];

//This array holds the relationship between the page variable and the template to load.. This info could also be retrieved from a db
$menu = array (
‘home’ => ‘home.tpl’,
‘about us’ => ‘aboutus.tpl’,
‘our system’ => ’system.tpl’,
‘products’ => ‘products.tpl’
);

//Check if the requested page was found in the menu
if ( array_key_exists ( $page_request, $menu ) )
$template = $menu[$page_request];
//If not set the default page
else
$template = ‘home.tpl’;

//Assign info to Smarty and display
$smarty->compile_id = $template;
$smarty->caching = 1;
$smarty->assign(’menu’, $menu);
$smarty->assign(’template’, $template);
$smarty->assign(’page_var’, $page_var);
$smarty->display(’index.tpl’);
?>

index.tpl

Code:
{include file=”menu.tpl”}
{include file=$template}

menu.tpl

Code:
{* We generate the menu list from the available pages in the menu *}
<ul id=”navigation”>
{foreach key=url_val item=template_name from=$menu}
<li>
<a href=”{$SCRIPT_NAME}?{$page_var}={$url_val}”>
{$url_val}<br />
</a>
</li>
{/foreach}
</ul>

tags: ,
posted in Guides, Programming by Owen

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
© 2008 - 2012 — All Rights Reserved — Ideamesh, Inc. 22 queries. 0.312 seconds.