Mished  

Home Articles Register

Reply
Old 04-05-2008, 06:26 PM
 
Default Database Driven Template Engine

This tutorial takes you through a PHP & MySQL powered template engine. The engine allows you to seperate code and design entirely.

First you need to download the attached project files, and run the "symplyte.sql" commands to set up your database.


PHP Code:
<?
error_reporting
(E_ALL);

mysql_connect("server""username""password") or die (mysql_error());
mysql_select_db("database") or die (mysql_error());

//These are all the templates used in this script.
$templates = array(
    
'homepage',
    
'menu'
);

class 
engine{

    var 
$templatecache = array();
    var 
$uncached = array();

    
//This function will take all of the names of the templates, and pull them from the database. It will then store them as strings in a variable called "$templatecache" for later use
    
function cachetemplates($templates){

        
$names implode("','"$templates);
        
$result mysql_query("SELECT template, templatename FROM templates WHERE templatename IN('$names')") or die (mysql_error());

          while(
$row mysql_fetch_array($result)){
            
$this->templatecache[$row['templatename']] = $row['template'];
        }        
    }

    
//This function will check the template cache for a requested template.
    //If not found  the function will query the database for the requested template and add it to the template cache.
    //It is advised that you add all templates to the $templates array to avoid excessive queries.
    
function fetchtemplate($template){
        if(!isset(
$this->templatecache[$template])){
            
//Get missing template from database
            
$result mysql_query("SELECT template, templatename FROM templates WHERE templatename = '" addslashes($template) . "'");
            
$row mysql_fetch_array($result);
            
//Add missing template to templatecache so it does not need to be called again.
            
$this->templatecache[$row['templatename']] = $row['template'];
            
$this->uncached[] = $row['templatename'];
            
$template $row['template'];
        } else {
            
$template $this->templatecache[$template];
        }
        
$template addslashes($template);    
        return 
$template;
    }
    
    
//This basically prints out a page, and any warnings about uncached templates.
    
function printoutput($page){
        print(
$page);
    }
}

$templatetastic = new engine();
//This pulls all the templates needed from the database.
$templatetastic->cachetemplates($templates); 

//This sets the date within the page. This shows how variables are used within the templates. This could be any data you want - news, articles, page content etc. Just pull it from the database, assign it to a variable, and place the variable in your template where you want it.
$dom date("d");
$moy date("M");

//Here we load the menu. If you actually look at the templates, you will see two templates. Menu, and Homepage. First if you look at 'menu' you will find a list of links, and then if you look at 'homepage' you will see a '$menu' variable within the template. when you load the 'menu' template it assigns it to the $menu variable...
eval('$menu = "' $templatetastic->fetchtemplate('menu') . '";');
//...and when we finally print the page out, we take the '$menu' variable and insert it into the 'homepage' template.
eval('$templatetastic->printoutput("' $templatetastic->fetchtemplate("homepage") . '");');
//this way you can add many templates, and sub-templates. Anything you need html code for - create a template.
?>
I am currently working on a full engine that eventually will be downloadable. This, and This tutorial's files are distributed under the Creative Commons Licence.
Click here for the Symplyte website
Attached Files
File Type: zip project_files.zip (14.3 KB, 68 views)
Reply With Quote
Old 04-08-2008, 05:36 PM
 
Default

Mished,

For the record, I posted your article in several high traffic websites:
Hopefully a few will step in and kick this off, get it kicking.

http://www.sitepoint.com/forums/showthread.php?t=541320
http://www.programmingtalk.com/showthread.php?p=144317
http://forums.devnetwork.net/viewtopic.php?f=2&t=81055
http://www.dynamicdrive.com/forums/s...d.php?p=138369
http://www.openwebdesign.org/forum/s...=4474#post4474

Please update that link or use a refresh tag to the new
page (don't kill that url).

Cal

Last edited by calfellows : 04-11-2008 at 01:38 PM.
Reply With Quote
Old 04-10-2008, 07:47 PM
 
Default Template Engine

Sir,
I am following this item, and hopefully
others will step in and contibute.
Cal

Last edited by calfellows : 04-12-2008 at 11:20 PM.
Reply With Quote
Old 04-10-2008, 08:23 PM
 
Default

jeez .. I need to revise my code! I wrote this rather quick!
Reply With Quote
Old 04-11-2008, 09:27 PM
 
Default

updated code.
Reply With Quote
Old 04-11-2008, 10:42 PM
 
Default

Chris,

Great. Installed and working, and I'm about to add
some content to the dbase.

Many Thanks,
Cal

Last edited by calfellows : 04-12-2008 at 11:21 PM.
Reply With Quote
Old 04-11-2008, 11:56 PM
 
Default

Chris,

Instead of having to constantly add and maintain templates
on that cache array listing, why not have the script populate
and maintain it's own list?

Great!!!!!
Cal

Last edited by calfellows : 04-12-2008 at 11:21 PM.
Reply With Quote
Old 04-12-2008, 08:07 AM
 
Default

Quote:
Originally Posted by calfellows View Post
Chris,

Instead of having to constantly add and maintain templates
on that cache array listing, why not have the script populate
and maintain it's own list?

I see that you completely removed $_GET. Independent pages/urls?

The CSS can also go into the template table, and there are
several ways to do this:

1. Add this to head tags




2. Add this to head tags


3.Save the above as $csstagged (not recommended).
4. Use css import tags instead of #1 linkref tags

Great!!!!!
Cal

how you design your page is entirely up to you - the html supplied is only an example, and is not intended to be used (unless you really want to).

yes, I agree that the CSS could be placed in a new template - this would allow site-wide changes of the style.

I quite commonly split all my pagews up into the following templates:

$header
$footer
$style
$headinclude
$navigation

and then have my main $content.

i removed the $_GET as it was not really required to demonstrate the engine - the engine was designed barebones, so any code you wish to add then please do so.
Reply With Quote
Old 04-12-2008, 08:07 AM
EdR
 
Default

This tutorial is a *BAD* idea and demonstrates shockingly bad design, ideas, and code practices. Not that bad PHP is a surprise, but the point stands. You show little skill with the language and obviously do not understand how the LAMP stack works.

You should *never* be using raw MySQL queries unless you know what you are doing; you obviously do not. You should always be using a wrapper to allow for formatted queries in the form of prepared statements, specifically with PDO ( http://php.net/pdo ) or MDB2 ( http://pear.php.net/MDB2 ).

If you *are* going to use raw MySQL queries, you need to be at least somewhat cognizant of failure. This code is ripe for SQL injection when used by a less-than-competent programmer; a function to neuter any data passed as a query string is essential. (You do not need such a function when using PDO or MDB2; when you pass the prepared statement a variable it automatically handles variable neutering.) Given a naive user of this code, I would expect them to simply pass the value of a $_GET entry into engine::fetchtemplate(), at which point I simply pass the literal shown below in as that GET value:

unimportant'; EMPTY templates; SELECT * FROM templates WHERE templatename = '

The above string would cause your query to empty your database. Something tells me that's not quite a good idea.

Furthermore, the entire idea behind your incredibly basic "system" is foolish. Unless you know why you are storing your *static pages* as database entries, you're doing it wrong. It isn't "easier to manage and edit"; that's preposterous when you have the option of tools with built-in SFTP controls. This is wankery for the sake of wankery. It is slower than using static files unless you have an enormous number of templates (and even then the benefit is on the order of microseconds), it is exponentially less reliable, and your perceived "ease of management" is a crock.

(Oh, and a tip: this doesn't "separate code and design" at all.)

Learn to program and learn to think before writing "tutorials" that will be more likely to harm learning programmers than help them. I'm sorry to be a bit of a twat, but teaching people wrongly is far worse than not teaching them at all.
Reply With Quote
Old 04-12-2008, 09:49 AM
 
Default

Edr and all,

A better approach would have been simply to offer specific suggestions or chunks for the project. I've participated in several such projects as a html page designer only; and my interest is mainly to see/learn and know exactly what's under the hood Look at the size of the file, 2042 bytes. Wordpress/Smarty/Joomla is what, 10MB, and with their own programming language

Traffic to this article has been significant; would actually pay the hosting and domain fees, and then some.

Keep up the good work Chris. Add a version #, update link, copyright notice, mandatory credit notice/warning, and instructions/suggestions to the top of the script. You might also consider storing your download link at http://sourceforge.net/ , popular thing to do, and helps with exposure, traffic, and design/support/suggestions.

EDr, please stick around, offer specifics to secure the current 2kb, and to implement a respectable front controller script.......

http://tinyurl.com/59lq3w
Regards,
Cal

Last edited by calfellows : 04-12-2008 at 10:12 AM.
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump


All times are GMT. The time now is 07:26 AM.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Display Pagerank
Web Design By Icora
Inactive Reminders By Icora Web Design