Smarty Forum Index Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon.

How to create a site through one index.php controller file
Goto page 1, 2  Next
 
This forum is locked: you cannot post, reply to, or edit topics.   This topic is locked: you cannot edit posts or make replies.    Smarty Forum Index -> Tips and Tricks
View previous topic :: View next topic  
Author Message
TGKnIght
Smarty Junkie


Joined: 07 Sep 2005
Posts: 580
Location: Philadelphia, PA

PostPosted: Wed May 31, 2006 5:46 am    Post subject: How to create a site through one index.php controller file Reply with quote

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>

_________________
Smarty site with one index.php controller file
Working with MySQL and Smarty
SmartyColumnSort
Custom Smarty Javascript Debug Template
Back to top
View user's profile Send private message Visit poster's website
Phunky
Smarty Rookie


Joined: 19 Apr 2007
Posts: 5

PostPosted: Thu Apr 19, 2007 1:10 pm    Post subject: Reply with quote

How would you go about using this for including dynamic pages?

Lets say we was including 'news.tpl' which would list some news items pulled out of a database.

Ideally we would want to keep the database logic in 'news.php' with 'news.tpl' just having the presentation elements.

I cant seem to pass any vars through to the included .tpl file Sad
Back to top
View user's profile Send private message
Celeb
Administrator


Joined: 17 Apr 2007
Posts: 1025
Location: Vienna

PostPosted: Thu Apr 19, 2007 2:25 pm    Post subject: Reply with quote

I don't know if this is a very smart approach, but maybe you could do something like this:

You've got a news.tpl file to list your news items.
Then you've got a news.php file to get them out of the database and fill your template variables.

Now in index.php you tell index.tpl to include news.tpl and additionally you include news.php in index.php.

index.php
Code:
include ('news.php');
$smarty->assign('template', 'news.tpl');


Now all the variables news.php assignes should be available in news.tpl.
Back to top
View user's profile Send private message
Phunky
Smarty Rookie


Joined: 19 Apr 2007
Posts: 5

PostPosted: Thu Apr 19, 2007 3:04 pm    Post subject: Reply with quote

That does work, but i cant help but think this is the wrong way to approach it.

I guess what i need is a wrapper or something to setup all the MySQL and other settings that are global throughout the differnt elements of the site and then just call the .php and .tpl few Smarty as you normally would
Back to top
View user's profile Send private message
Phunky
Smarty Rookie


Joined: 19 Apr 2007
Posts: 5

PostPosted: Thu Apr 19, 2007 3:16 pm    Post subject: Reply with quote

Just had a thought, if i was to push everything through classes that was then loaded in the index.php i should then be able to gather all the data i need within any .tpl that is included in the index.tpl?
Back to top
View user's profile Send private message
TGKnIght
Smarty Junkie


Joined: 07 Sep 2005
Posts: 580
Location: Philadelphia, PA

PostPosted: Thu Apr 19, 2007 11:35 pm    Post subject: Reply with quote

In the one framework I've built I do it like Celeb's example.

I am currently working on a different framework and have not yet determined how I want to approach it.

The nice thing about having everything go through 1 index.tpl is that your debug template will have every var in it all at once, instead of seperate ones for each $smarty->display() call.
_________________
Smarty site with one index.php controller file
Working with MySQL and Smarty
SmartyColumnSort
Custom Smarty Javascript Debug Template
Back to top
View user's profile Send private message Visit poster's website
czarnowski
Guest





PostPosted: Sat Apr 21, 2007 1:07 pm    Post subject: Reply with quote

I have made a test script with minimal changing:

Code:

<?php
$timeparts = explode(" ", microtime());
$starttime = $timeparts[1].substr($timeparts[0], 1);
include('Smarty.class.php');
$smarty =& new Smarty();
$smarty->compile_check=false;
$page_var = 'page';
$page_request = $_REQUEST[$page_var];
$root_url ="http://".$_SERVER['SERVER_NAME'].'/simple';

$inhalt = array (
            'Home' => 'home.tpl',
            'Firma' => 'firma.tpl',
            'Produkte' => 'produkte.tpl',
            'Marmor' => 'marmor.tpl',
            'Stein' => 'stein.tpl',
            'Eisen' => 'eisen.tpl',
            'Bleche' => 'bleche.tpl',
            'Kontakt' => 'kontakt.tpl'
            );

$menu = array (
'SECTION',
'Home',
'Firma',
'Produkte',
'SECTION',
'Marmor',
'Stein',
'Eisen',
'ENDSECTION',
'Bleche',
'Kontakt',
'ENDSECTION'
);

if ( array_key_exists ( $page_request, $inhalt ) )
   $template = $inhalt[$page_request];
else
   $template = 'home.tpl';

$smarty->assign('root_url', $root_url);
$smarty->assign('menu', $menu);
$smarty->assign('template', $template);
$smarty->assign('page_var', $page_var);
$smarty->display('index.tpl');
$timeparts = explode(" ", microtime());
$endtime = $timeparts[1].substr($timeparts[0], 1);
$gesamt = $endtime-$starttime;
echo "<!--Generated in ".$gesamt." seconds and ".(function_exists('memory_get_usage')?memory_get_usage(true):'n/a')." bytes of memory-->";
if (function_exists('memory_get_peak_usage'))
        echo "\n"."<!--Peak memory needed ".memory_get_peak_usage(true).' Bytes.-->';
?>


The menu is a comnination of all and another idea from the forum.
Here the template:





Code:
{foreach from=$menu item=section_item}
{if $section_item=='SECTION'}
   <ul>{capture name=closing} {/capture}
{elseif $section_item=='ENDSECTION'}
   </li></ul>
{else}
   {$smarty.capture.closing}
        <li><a href="{$root_url}/index.php?page={$section_item}">{$section_item}</a>
   {capture name=closing}</li>{/capture}
{/if}
{/foreach}


and here you can see a small demo

http://powercms.org/simple

and here the same demo with template lite

http://powercms.org/simplel

template lite has here only little advantages with speed and memory, so it is not realy interesting me.
Back to top
eth0
Smarty n00b


Joined: 03 May 2007
Posts: 3

PostPosted: Wed May 09, 2007 10:10 pm    Post subject: Reply with quote

My index.php
Code:
        include("./inc/global.php");

        if ( $ifc0nfig->smarty->template_exists( $ifc0nfig->navi->pages["currentTPL"] ) )
        {
                if ( file_exists( $ifc0nfig->navi->pages["currentPHP"] ) )
                {
                        include( $ifc0nfig->navi->pages["currentPHP"]  );
                }

                $ifc0nfig->smarty->assign( "content" , $ifc0nfig->smarty->fetch( $ifc0nfig->navi->pages["currentTPL"] ) );
        }
        else
        {
                $ifc0nfig->smarty->assign( "content" , $ifc0nfig->smarty->fetch( $ifc0nfig->navi->pages["404"] ) );
        }

        $ifc0nfig->smarty->display( "index.tpl" );


My global.php just initializes classes such as smarty, navigation, MySQL, etc. All called through the $ifc0nfig object.

My navi.php
Code:
<?php

        if( !defined( "ifc0nfig" ) )
        {
                // naughty, naughty...
                exit( "Hello :-)" );
        }

        class navi
        {
                var $currentPage = null;
                var $menuArray = null;
                var $pages = null;

                function navi( &$ifc0nfig )
                {
                        $getPage = isset( $_GET["p"] ) ? $_GET["p"] : "home";

                        $queryRes = $ifc0nfig->MySQL->doQuery( "SELECT `m_id` , `name` , `display_name` , `hide` FROM `menu`" );

                        while( $row = $ifc0nfig->MySQL->fetchAssoc( $queryRes ) )
                        {
                                $row["selected"] = false;
                                $this->menuArray[] = $row;
                        }

                        foreach ($this->menuArray as $key => $val)
                        {
                                if( $getPage != NULL && $getPage == $val["name"] )
                                {
                                        $this->menuArray[$key]["selected"] = true;
                                        $this->currentPage = $this->menuArray[$key]["name"];
                                }
                        }

                        //
                        // Setup default pages array
                        //
                                $this->pages["404"] = "page/404.tpl";
                                $this->pages["currentTPL"] = "page/" . $this->currentPage . ".tpl";
                                $this->pages["currentPHP"] = ROOT_DIR . "tpl/php/" . $this->currentPage . ".php";
                        //

                        $ifc0nfig->smarty->assign("menuArray" , $this->menuArray );
                }
        }

?>


My index.tpl just has the usual stuff and prints out $content and $menuArray like so:

Code:

{foreach item=menu from=$menuArray}
        {if $menu.hide == false}
                <li{if $menu.selected === true} class="selected"{/if}><a href="?p={$menu.name}">{$menu.display_name}</a></li>
        {/if}
{/foreach}

{content}


Does the job nicely Smile
Back to top
View user's profile Send private message
chantown
Smarty Rookie


Joined: 30 Jul 2007
Posts: 5

PostPosted: Sat Aug 25, 2007 4:12 am    Post subject: Reply with quote

Is there any disadvantage of using this index.php "controller" method?

(I know Joomla uses this)
Back to top
View user's profile Send private message
manjcupuo
Smarty n00b


Joined: 29 Oct 2007
Posts: 1

PostPosted: Mon Oct 29, 2007 4:19 am    Post subject: Reply with quote

chantown wrote:
Is there any disadvantage of using this index.php "controller" method?

(I know Joomla uses this)


According to a source, it makes it very easy to deal with “global operations”, which have to happen on every page of your site, such as logging, authentication / session checking and dealing with such things as HTTP client cache headers. But such problem can be solve.
_________________
All about phentermine diet pills. cheap phentermine for quick weight loss.
Back to top
View user's profile Send private message
Babysittah
Smarty n00b


Joined: 28 Nov 2007
Posts: 3

PostPosted: Wed Nov 28, 2007 7:31 am    Post subject: Reply with quote

That'll be useful thing 4 me:) Thanx!
_________________
http://www.love-vs-hate.com/ - a sad
http://www.mybestcity.com/ - millionaire
http://www.newbabyassistant.com/ - here
Back to top
View user's profile Send private message
bladetmc
Smarty n00b


Joined: 20 Dec 2007
Posts: 3

PostPosted: Thu Dec 20, 2007 12:10 pm    Post subject: Reply with quote

manjcupuo wrote:
chantown wrote:
Is there any disadvantage of using this index.php "controller" method?

(I know Joomla uses this)


According to a source, it makes it very easy to deal with “global operations”, which have to happen on every page of your site, such as logging, authentication / session checking and dealing with such things as HTTP client cache headers. But such problem can be solve.


The only disadvantage is that it is getting complex Smile And a small security risk.

(When calling the controller or module way dynamically, u should be aware that the users cannot call stuff outside that specific filedir). Most common used fault is bypassing those with simple domain/controller/../uploaddir/somethingnaughty.php/ Smile

But i rather dont see J00mla, not a very good example. If u use one, there are others wich are better made then that. (Drupal, CakePHP, Zend, CodeIgniter).

Or make your own based on for example MVC model, but please make it all classes instead of the example above.

index.php should only contain:
include(myframework.php);

$f00 = new MyFrameWork();

Then do debugging, logging, database access etc (smarty isnt a part of it, especially when using MVC. Smarty is needed to do the View and should be called at the end of the chain Razz)
Back to top
View user's profile Send private message
Celeb
Administrator


Joined: 17 Apr 2007
Posts: 1025
Location: Vienna

PostPosted: Thu Dec 20, 2007 4:17 pm    Post subject: Reply with quote

Try monte's new project: http://www.tinymvc.com Very Happy
_________________
Darn computers always do what I tell them to instead of what I want them to do.
Back to top
View user's profile Send private message
bladetmc
Smarty n00b


Joined: 20 Dec 2007
Posts: 3

PostPosted: Thu Dec 20, 2007 5:06 pm    Post subject: Reply with quote

I already looked at it Smile Indeed very tiny, but didnt had time to test it tbh to see if it is as quick as he says it is.

But mine is better, but aint open source. Only reason that the more ppl know the code, the unsecure it is (its called bladesdefence pattern Razz).

Big Disadvantage, i have todo everything myself Very Happy
Back to top
View user's profile Send private message
jetmuzer
Smarty n00b


Joined: 16 Dec 2007
Posts: 2
Location: UK

PostPosted: Thu Dec 20, 2007 5:45 pm    Post subject: Reply with quote

Thanks, that is very helpful listing Smile
_________________
music store mp3 music mp3 music download
Back to top
View user's profile Send private message Visit poster's website Yahoo Messenger
Display posts from previous:   
This forum is locked: you cannot post, reply to, or edit topics.   This topic is locked: you cannot edit posts or make replies.    Smarty Forum Index -> Tips and Tricks All times are GMT
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group
Protected by Anti-Spam ACP